27

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)
iwasrobbed
  • 46,496
  • 21
  • 150
  • 195

2 Answers2

32

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.

apneadiving
  • 114,565
  • 26
  • 219
  • 213
  • It is strange that the standard way doesn't work, but I'll go with `current_page?(root_path)` for now since it's nice and short. Thanks for the response! – iwasrobbed Mar 04 '11 at 03:26
  • `current_page?(root_path)` should be true only when `"/"` for current path, but not for `"/pages/main"` I guess. Is it any wrong to have `if controller_name == 'pages' && action_name == 'main'` here? – kangkyu Aug 14 '15 at 20:38
  • In my case I have a `Home#index` controller assigned to root which only redirects to, in this case, `Pages#main`. Then I use `current_page?(main_page_path)` assuming you created that route in `config/routes.rb` – Pedro Adame Vergara Mar 21 '17 at 11:02
4

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.

Darren
  • 41
  • 1