如何在Rails 4中为所有URL添加尾部斜杠?

4
我尝试在application.rb文件中添加这个内容。
config.action_controller.default_url_options = { :trailing_slash => true }

在routes.rb中添加:trailing_slash => true可实现此功能。

match '/download', to: 'welcome#download', via: 'get', :trailing_slash => true

但是似乎都不起作用。我在rails 4.0文档中搜索,但找不到相关信息。我错过了什么?
更新:
我尝试添加
Rails.application.default_url_options[:trailing_slash] = true

在整个项目中,我只能在filter_parameter_logging.rb中找到Rails.application.*,但它也不起作用。 我在这里的发布说明中找到了这行代码,我使用的是4.0.4版本。我把它添加到了错误的地方吗?而且我在重新检查之前已经重启了服务器。
很抱歉问一个简单的问题,但从我收集的信息来看,trailing_slash难道不应该在浏览器URL中反映出来吗,如果不是主要的话?因为这正是我需要的,以配合historyjs。

你是在说你的应用程序生成的URL吗? - phoet
@phoet 是的,我该怎么做才能让所有的“download”自动重定向到“download/”? - Lucia
我认为你应该在 Web 服务器层面上进行此操作,你在使用 nginx 吗? - complistic
4个回答

9

我认为你对:trailing_slash => true的意思有误。

它只是在你的路径助手末尾添加/。没有涉及重定向。

你的路由仍然可以响应带或不带尾随斜杠的请求。

如果你想要将所有非trailing_slash的URI(如/download)重定向到/download/,使用nginx http服务器,你需要像这样做:

rewrite ^([^.\?]*[^/])$ $1/ permanent;

你仍然需要在你的路由中添加 :trailing_slash => true,这样你的路径/url助手才能生成正确的URI(这样用户就不需要重定向)。

1
在Rails世界中,与PHP相反,所有应用程序逻辑都保存在应用程序内部,而不是Apache或nginx配置文件中。我认为这不是一个好的解决方案。 - Nowaker

2

Trailing_slash是指在名称后面添加/,例如page/,而不是像/page

您错误地给出了路由。

请将其更改为

match 'download/', to: 'welcome#download', via: 'get', :trailing_slash => true

还有另一种方法可以通过直接给你的link_to助手提供trailing_slash => true选项来实现此目的。

link_to 'Downloads', downloads_path(:trailing_slash => true)

虽然这适用于Rails 3,但不确定是否适用于Rails 4。

更多细节请参见此处


1

我正在使用 rails 4.0.2,对我来说它是正常工作的。

routes.rb

       get 'admin/update_price_qty' => 'admin#update_price_qty', :trailing_slash => true,:as  => "price"

在控制台中:-
     irb(main):003:0* app.price_path
     => "/admin/update_price_qty/"

routes.rb

   match '/download', to: 'welcome#index', via: 'get', :trailing_slash => true,:as => "welcome_price"

在控制台中:-
   `irb(main):002:0> app.welcome_price_path
    => "/download/"`

但我尝试在application.rb中添加了这个。
config.action_controller.default_url_options = { :trailing_slash => true }

不工作。


我是否必须在irb中看到结果?trailing_slash不应该在浏览器地址栏中添加斜杠吗?这就是我一开始所需要的,因为我将需要使用history.js来检测URL更改。但是我没有看到任何变化,即使使用了:trailing_slash => true - Lucia

0

您可以将以下行添加到config/application.rb文件中:

config.action_controller.default_url_options = { trailing_slash: true }

如果你这样做,当你在控制器或者帮助类中调用Rails路径助手时,生成的路径将会以/结尾:
class ApplicationController
  def index
    download_path # returns "/download/"
  end
end

module PathHelper
  def path
    download_path # returns "/download/"
  end
end

如果您需要在控制器和帮助程序之外使用路径助手,则需要include Rails.application.routes.url_helpers,但显然,这会忽略上面的trailing_slash配置:
class SomeClass
  include Rails.application.routes.url_helpers

  def path
    download_path # returns "/download"
  end
end

在这种情况下,您应该将{ trailing_slash: true }作为参数添加:
class SomeClass
  include Rails.application.routes.url_helpers

  def path
    download_path(trailing_slash: true) # returns "/download/"
  end
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接