13

I'm porting the existing website from PHP to Ruby on Rails 3 and I have to keep the urls unchanged.

I have the route:

get 'companies/' => 'companies#index', :as => :companies

In a view file I have:

link_to 'Companies', companies_path

and this generates the url "http://website.com/companies" instead of "http://website.com/companies/".

I want the slash at the end of the url. Is it possible?

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

4 Answers4

37

You can add this to your application.rb:

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

This way all routes will be generated with a trailing slash automatically, with no need to modify each link in your project.

David Morales
  • 17,816
  • 12
  • 77
  • 105
23

Simply do as follows:

link_to 'Companies', companies_path(:trailing_slash => true)

Documentation here.

apneadiving
  • 114,565
  • 26
  • 219
  • 213
  • Awesome! I didn't know about the `:trailing_slash` option. – Ryan Bigg Jun 26 '11 at 08:53
  • 1
    Thanks a lot! It works! But maybe you know is there the way to make rails automatically add trailing slash if it is present in the url pattern in routes.rb? – Aleksandr Shvalev Jun 26 '11 at 08:54
  • If you know, please give me the solution here: [link](http://stackoverflow.com/questions/6486758/how-to-make-rails-do-not-ignore-trailing-slashes-in-the-routes) – Aleksandr Shvalev Jun 26 '11 at 21:10
3

I couldn't find any references, but adding trainling_slash: true to the route definition also works (and avoids repeating oneself).

get 'companies/' => 'companies#index', :as => :companies, :trailing_slash => true

This was tested with Rails 3.2.13:

rails c
1.9.3p327 :005 > app.companies_path
=> "http://www.example.com/companies/
Abel Muiño
  • 7,611
  • 3
  • 24
  • 15
0

For rails 3.2:

Rails.application.routes.default_url_options[:trailing_slash]= true
blub
  • 8,757
  • 4
  • 27
  • 38