What's the difference between example.com/controller and example.com/controller/ in Rails?

断了今生、忘了曾经 提交于 2020-01-24 05:43:25

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/1263369/whats-the-difference-between-example-com-controller-and-example-com-controller

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