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)
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.
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