Rails: Knowing the current Action in a View
Posted on January 18, 2007
Filed Under /dev/ruby | 486 views |
At some point you, like me, may want to do something in a Rails view that is dependent upon the current action. But how to know what the currect action is (without doing some ugly URL parsing)?
The Highlight link for current action over on Code Snippets has the solution.
Add the following to your application.rb controller:
RUBY:
-
private
-
before_filter :instantiate_controller_and_action_names
-
-
def instantiate_controller_and_action_names
-
@current_action = action_name
-
@current_controller = controller_name
-
end
You should now have @current_action and @current_controller available to all your views and helpers.
Comments
4 Responses to “Rails: Knowing the current Action in a View”
Leave a Reply
Thanks for the idea. I wish Rails featured a smartest way to access these variables, but it will have to do.
I had been searching for this same thing, and I found it!
From http://snippets.dzone.com/posts/show/4391
In a view, you can use:
(Previous comment was truncated because it didn’t like my < % = stuff
Good grief. Cut off again.
controller.controller_name
controller.action_name