问题
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