简体   繁体   English

如何使Rails不忽略路线中的尾部斜杠?

[英]How to make Rails do not ignore trailing slashes in the routes?

For example, I have the rote in routes.rb: 例如,我在routes.rb中有死记硬背:

get 'companies/' => 'companies#index', :as => :companies

There is the way to generate link with the trailing slash (like "http://website.com/companies/"): 有一种方法可以生成带有斜杠的链接(例如“ http://website.com/companies/”):

link_to 'Compaines', companies_path(:trailing_slash => true)

But I want Rails to generate link with trailing slash if it is present in the route by default: 但我希望Rails生成带有尾部斜杠的链接(如果默认情况下该路由中存在该链接):

link_to 'Companies', companies_path

Now it generates something like "http://website.com/companies". 现在,它会生成类似“ http://website.com/companies”的内容。 How to fix it? 如何解决?

I'm not sure why you need your routes to understand that there is a trailing slash. 我不确定您为什么需要自己的路线来理解是否有斜杠。 It doesn't matter if you put the trailing slash to Rails. 是否将尾部斜杠放在Rails上都没有关系。 It should respond either way. 它应该以任何方式响应。

If you want all of your links to have a trailing slash, you can put the following in your application.rb: 如果希望所有链接都带有斜杠,可以在application.rb中添加以下内容:

config.action_controller.default_url_options = { :trailing_slash => true }

This will make all links generated by Rails have a trailing slash. 这将使Rails生成的所有链接都带有斜杠。 Now, if you're trying to reject any route that does not contain a trailing slash, then I'm not sure about how to do that. 现在,如果您要拒绝任何不包含斜杠的路由,那么我不确定该怎么做。

How about implementing a helper called link_to_with_trailing_slash(name, path)? 如何实现一个名为link_to_with_trailing_slash(name,path)的助手?

def link_to_with_trailing_slash(name, path)
  link_to(name, "#{path}/"
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM