本文介绍了Rails 中的 example.com/controller 和 example.com/controller/有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 PostsController,对示例来说不是必需的,但在我粘贴代码片段时会有所帮助,我使用 current_page? 来,顾名思义,找出正在显示的页面.我得到的结果似乎很奇怪.

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? 如果我去 /posts/posts/ 会返回不同的答案.

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

如果我转到/controller(没有尾部斜杠),current_page? 将返回 true.但是,如果我转到/controller/,它将返回 false.

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.

我正在使用 Rails 2.3.2 和 这张票 是唯一看起来很接近的东西.唯一的评论者认为 current_page 应该如果两个 URL 都引用同一个 RESTful 对象,则将它们视为同一页面".

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.

推荐答案

rails routing 会容忍尾部斜杠,但是当你通过 :action =>'索引', :controller =>'posts'url_for(使用标准路由).

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

根据current_page?documentation 它只是从传递的参数生成一个 url,然后与当前请求 url string.由于此生成的 url 将没有尾部斜杠,因此当当前 url 为/controller 时返回 true,当/controller/

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:

  • 比较参数,而不是生成的 url
  • 从/controller/重定向到/controller.如果您也为 SEO 进行页面缓存等,这实际上是一个好主意
  • 我确信还有其他方法可以像往常一样:)

这篇关于Rails 中的 example.com/controller 和 example.com/controller/有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:14