简体   繁体   中英

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

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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