Ruby-on-rails Rails current_page?与 controller.controller_name 对比
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5186613/
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 current_page? versus controller.controller_name
提问by iwasrobbed
I'm implementing current_page?in a view to test if the current controller and action is equal to a certain value, however it won't return true when on that controller/action combination.
我正在实施current_page?以测试当前控制器和操作是否等于某个值,但是在该控制器/操作组合上它不会返回 true。
- if current_page?(:controller => 'pages', :action => 'main')
# doesn't return true when on that controller/action combination
The only way it is working is if I use a bit more verbose method like so:
它工作的唯一方法是,如果我使用更详细的方法,如下所示:
- if controller.controller_name == 'pages' && controller.action_name == 'main'
# this works just fine
Is my syntax wrong or is there something else happening here? Is there a better way of doing this, such as setting a BOOL or is this the proper way?
我的语法错误还是这里发生了其他事情?有没有更好的方法来做到这一点,比如设置一个 BOOL 或者这是正确的方法?
The end goal is to only show a certain header on the main landing page while showing a different header on all other pages.
最终目标是只在主着陆页上显示某个标题,而在所有其他页面上显示不同的标题。
Edit: Relevant output from rake routes:
编辑:相关输出rake routes:
pages_main GET /pages/main(.:format) {:controller=>"pages", :action=>"main"}
root /(.:format) {:controller=>"pages", :action=>"main"}
Also, this is the server output upon rendering:
此外,这是渲染时的服务器输出:
Started GET "/" for 127.0.0.1 at 2011-03-03 16:54:40 -0500
Processing by PagesController#main as HTML
Rendered pages/main.html.haml within layouts/application (203.8ms)
回答by apneadiving
current_page?(root_path)works fine.
current_page?(root_path)工作正常。
But I can't make it work with :controllerand :action
但我不能让它:controller和:action
It seems the helper expects a string, so:
似乎助手需要一个字符串,所以:
current_page?(url_for(:controller => 'pages', :action => 'main'))
works fine too.
工作正常。
Weird contradiction with the doc.
与doc奇怪的矛盾。
回答by Darren
I had this issue when I had 2 routes that were very similar. Check this out:
当我有 2 条非常相似的路线时,我遇到了这个问题。看一下这个:
match '/galleries/sales' => 'galleries#sales', :as => 'gallery_sales'
match '/galleries/sales/:id' => 'galleries#sales', :as => 'gallery_category_sales'
My controller action handled the output depending on params, and I originally did this b/c I didn't want duplication.
我的控制器操作根据参数处理输出,而我最初是这样做的 b/c 我不想重复。
When I did:
当我这样做时:
current_page?(:controller => 'galleries', :action => 'sales', :id => id)
It didn't return true when it should have, so I created a different route and action and it worked fine.
它在应该返回的时候没有返回 true,所以我创建了一个不同的路由和操作,它运行良好。

