How to generate links with trailing slash in Rails 3?

旧时模样 提交于 2019-12-17 18:19:31

问题


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?


回答1:


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.




回答2:


Simply do as follows:

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

Documentation here.




回答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/



回答4:


For rails 3.2:

Rails.application.routes.default_url_options[:trailing_slash]= true


来源:https://stackoverflow.com/questions/6482693/how-to-generate-links-with-trailing-slash-in-rails-3

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