views:

67

answers:

1

Hi there,

I have a PostsController, not essential to the example but will help when I paste snippets, and I'm using current_page? to, as the name implies, figure out what page is being displayed. I'm getting what seem like weird results.

current_page? will return different answers if I go to /posts vs. /posts/.

As a test, on the index view for my controller I am simply calling

current_page?(:action => 'index')

If I go to /controller (with no trailing slash), current_page? will return true. However, if I go to /controller/, it will return false.

Tailing the log shows that both do in fact hit the same action

Processing PostsController#index (for 127.0.0.1 at 2009-08-11 18:28:12) [GET]
  Parameters: {"action"=>"index", "method"=>:get, "controller"=>"posts"}

The action produces the same results for both, as to be expected.

I'm using Rails 2.3.2 and this ticket is the only thing that seems close. The only commenter thinks that current_page should "consider two URLs to be the same page if they both refer to the same RESTful object".

Thanks for any insight into this.

+2  A: 

rails routing will tolerate the trailing slash but it will not be generated when you pass :action => 'index', :controller => 'posts' to url_for (with standard routes).

according to current_page? documentation it just generates a url from the passed arguments and then compares to the current request url string. since this generated url will not have the trailing slash it will return true when current url is /controller and false when /controller/

There are several ways you can solve your problem:

  • compare the params, not generated url
  • redirect from /controller/ to /controller. This is actually a good idea if you do page caching etc. also for SEO
  • I'm sure there are other ways as always :)
Vitaly Kushner
That makes sense. Should have probably checked the source of current_page? Thank you very much!
theIV