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

妖精的绣舞 提交于 2019-12-24 01:24:15

问题


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?


回答1:


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:

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

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.




回答2:


How about implementing a helper called link_to_with_trailing_slash(name, path)?

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


来源:https://stackoverflow.com/questions/6486758/how-to-make-rails-do-not-ignore-trailing-slashes-in-the-routes

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