如何让 Rails 不忽略路由中的尾部斜杠?
例如,我在routes.rb中有死记硬背:
get 'companies/' => 'companies#index', :as => :companies
有一种方法可以生成带有尾部斜杠的链接(如“http://website.com/companies/”):
link_to 'Compaines', companies_path(:trailing_slash => true)
但我希望Rails生成带有尾部斜杠的链接,如果默认情况下它存在于路由中:
link_to 'Companies', companies_path
现在它会生成类似“http://website.com/companies”的内容。如何修复它?
For example, I have the rote in routes.rb:
get 'companies/' => 'companies#index', :as => :companies
There is the way to generate link with the trailing slash (like "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:
link_to 'Companies', companies_path
Now it generates something like "http://website.com/companies". How to fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道为什么你需要你的路线来理解有一个尾部斜杠。如果将尾部斜杠放在 Rails 中也没关系。无论哪种方式它都应该响应。
如果您希望所有链接都有一个尾部斜杠,您可以将以下内容放入 application.rb 中:
这将使 Rails 生成的所有链接都有一个尾部斜杠。现在,如果您尝试拒绝任何不包含尾部斜杠的路由,那么我不确定该怎么做。
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. 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:
This will make all links generated by Rails have a trailing slash. 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.
实现一个名为 link_to_with_trailing_slash(name, path) 的助手怎么样?
How about implementing a helper called link_to_with_trailing_slash(name, path)?