Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Get the controller and action of the current request

In my Rails application, I use <html id=<%= params[:controller] + "_" + params[:action] %> in views/layouts/application.html.erb.

The strange thing is, the values of params[:controller] and params[:action] always lag by 1 request if it is anywhere above the opening <body> tag.

So if I'm on users/1, but I came from users/, the values above opening <body> will be controller: "users" and action: "index". Shouldn't params[:action] be "show"?.

Then if I refresh the page, it 'catches up' and correctly has controller: "users" and action: "show".

Why is this happening? How can I get the current requests controller and action? Will these params not be updated until the first time yield is called?

like image 541
Don P Avatar asked Jan 28 '14 07:01

Don P


2 Answers

For the controller, you have access to the local instance controller. If you want the full name of it, you'll need to use something like controller.class.name.split("::").first which will give you UsersController in your example. If you just wanted users to be returned you could use controller.controller_name

For the action you can use controller.action_name

UPDATE:

Please try these in your view and see if they're also lagging:

<p><%= controller_name %></p>
<p><%= action_name %></p>

I suspect they both delegate to the controller mentioned earlier in my answer, but it's worth trying.

like image 99
Jon Avatar answered Sep 22 '22 23:09

Jon


It was turbolinks. Turn off turbolinks and you're good to go. http://blog.steveklabnik.com/posts/2013-06-25-removing-turbolinks-from-rails-4

like image 32
Don P Avatar answered Sep 21 '22 23:09

Don P