Rails - controller action name to string
Ruby on-RailsFunctionRuby on-Rails Problem Overview
I have a Rails question.
How do I get a controller action's name inside the controller action?
For example, instead of
def create
logger.info("create")
end
I want to write something like
def create
logger.info(this_def_name)
end
What is a way to get this_def_name
?
Ruby on-Rails Solutions
Solution 1 - Ruby on-Rails
Rails 2.X: @controller.action_name
Rails 3.1.X: controller.action_name
, action_name
Rails 4.X: action_name
Solution 2 - Ruby on-Rails
In the specific case of a Rails action (as opposed to the general case of getting the current method name) you can use params[:action]
Alternatively you might want to look into customising the Rails log format so that the action/method name is included by the format rather than it being in your log message.
Solution 3 - Ruby on-Rails
controller name:
<%= controller.controller_name %>
return => 'users'
action name:
<%= controller.action_name %>
return => 'show'
id:
<%= ActionController::Routing::Routes.recognize_path(request.url)[:id] %>
return => '23'
Solution 4 - Ruby on-Rails
This snippet works for Rails 3
class ReportsController < ApplicationController
def summary
logger.debug self.class.to_s + "." + self.action_name
end
end
will print
> . . .
> ReportsController.summary
> . . .
Solution 5 - Ruby on-Rails
mikej's answer was very precise and helpful, but the the thing i also wanted to know was how to get current method name in rails.
found out it's possible with self.current_method
easily found at http://www.ruby-forum.com/topic/75258
Solution 6 - Ruby on-Rails
You can get the Action Name like this
Controller Method
def abc
params[:action] #you can store this any variable or you can directly compare them.
ab == params[:action]
end
This supports from rails 4 to rails 6 versions.
Solution 7 - Ruby on-Rails
I just did the same. I did it in helper controller, my code is:
def get_controller_name
controller_name
end
def get_action_name
action_name
end
These methods will return current contoller and action name. Hope it helps