Is there a way to figure out what the current controller is from within the view?
For an example of why I would want to know this: if several controllers share the same layout, I may have a part in the layout ERB file where I want to highlight the current page's menu item based on the controller.
Maybe that is a bad approach. If so, what is the more preferred way to do this?
I'm interested to know about getting the name of the current controller either way, though.
(Obviously I could put something like @controller_name = 'users'
in each controller; but that seems like the sort of thing Rails would've already done behind the scenes. So I'm just wondering if there's a built-in way.)
In the Rails Guides, it says:
The params hash will always contain the :controller and :action keys, but you should use the methods controller_name and action_name instead to access these values
So let's say you have a CSS class active
, that should be inserted in any link whose page is currently open (maybe so that you can style differently) . If you have a static_pages
controller with an about
action, you can then highlight the link like so in your view:
<li>
<a class='button <% if controller.controller_name == "static_pages" && controller.action_name == "about" %>active<%end%>' href="/about">
About Us
</a>
</li>