Ruby-on-rails Rails:获取当前请求的控制器和动作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21399663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails: Get the controller and action of the current request
提问by Don P
In my Rails application, I use <html id=<%= params[:controller] + "_" + params[:action] %>in views/layouts/application.html.erb.
在我的 Rails 应用程序中,我<html id=<%= params[:controller] + "_" + params[:action] %>在 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.
奇怪的是,如果它位于开始标记上方的任何位置,则params[:controller]和的值params[:action]总是滞后 1 个请求。<body>
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"?.
因此,如果我在users/1,但我来自users/,则开头的值<body>将是控制器:“用户”和动作:“索引”。不应该params[:action]是“秀”吗?
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 yieldis called?
为什么会这样?如何获取当前请求控制器和操作?这些参数在第一次yield调用之前不会更新吗?
采纳答案by Don P
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
这是涡轮链接。关闭 turbolinks,你就可以开始了。http://blog.steveklabnik.com/posts/2013-06-25-removing-turbolinks-from-rails-4
回答by Jon
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("::").firstwhich will give you UsersControllerin your example. If you just wanted usersto be returned you could use controller.controller_name
对于控制器,您可以访问本地实例controller。如果你想要它的全名,你需要使用类似的东西controller.class.name.split("::").first,这会UsersController在你的例子中给你。如果你只是想users被退回,你可以使用controller.controller_name
For the action you can use controller.action_name
对于您可以使用的操作 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.
我怀疑他们都委托给我前面提到的控制器,但值得一试。

