2

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?

Aleksandr Shvalev
  • 1,005
  • 2
  • 11
  • 22

2 Answers2

7

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.

Sean Hill
  • 14,978
  • 2
  • 50
  • 56
  • The main reason a routing table should recognize a route with a trailing slash or not is that it might matter for SEO. If both slash and non-trailing-slash versions contain the same content and each returns 200 consider changing this behavior to reduce duplicate content and improve crawl efficiency. https://webmasters.googleblog.com/2010/04/to-slash-or-not-to-slash.html – dmmfll Apr 28 '18 at 16:45
-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
Peder
  • 2,739
  • 3
  • 31
  • 33