Rails: Knowing the current Action in a View

Posted on January 18, 2007
Filed Under /dev/ruby | 19,896 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:
  1. private
  2.   before_filter :instantiate_controller_and_action_names
  3.  
  4.   def instantiate_controller_and_action_names
  5.       @current_action = action_name
  6.       @current_controller = controller_name
  7.   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”

  1. Abel on March 22nd, 2008 4:31 am

    Thanks for the idea. I wish Rails featured a smartest way to access these variables, but it will have to do.

  2. Michael Teter on May 11th, 2008 1:24 pm

    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:

  3. Michael Teter on May 11th, 2008 1:25 pm

    (Previous comment was truncated because it didn’t like my < % = stuff :)

  4. Michael Teter on May 11th, 2008 1:26 pm

    Good grief. Cut off again.

    controller.controller_name
    controller.action_name

  • About

    This is an area on your website where you can add text. This will serve as an informative location on your website, where you can talk about your site.

  • Admin