Rails current_page? versus controller.controller_name

一世执手 提交于 2019-11-27 10:08:46

问题


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.

- 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?

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:

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)

回答1:


current_page?(root_path) works fine.

But I can't make it work with :controller and :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.




回答2:


I had this issue when I had 2 routes that were very similar. Check this out:

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.

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.



来源:https://stackoverflow.com/questions/5186613/rails-current-page-versus-controller-controller-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!