Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate links with trailing slash in Rails 3?

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?

like image 311
Aleksandr Shvalev Avatar asked Jun 26 '11 07:06

Aleksandr Shvalev


People also ask

How do you add a trailing slash to a URL?

A trailing slash is a forward slash (“/”) placed at the end of a URL such as domain.com/ or domain.com/page/. The trailing slash is generally used to distinguish a directory which has the trailing slash from a file that does not have the trailing slash.

Should I add trailing slash to URL?

If your site has a directory structure, it's more conventional to use a trailing slash with your directory URLs (for example, example.com/directory/ rather than example.com/directory ), but you can choose whichever you like. Be consistent with the preferred version. Use it in your internal links.

How do you fix trailing slash issues?

A 301 redirect is the best way to resolve duplicate content issues caused by trailing slashes. If you're just fixing one page, you'd redirect the duplicate copy to the version that matches your chosen URL structure. Most trailing slash issues however, affect many pages across a website.

What are slashes in URL?

The addition of a slash at the end of a URL instructs the web server to search for a directory. This speeds the web page loading because the server will retrieve the content of the web page without wasting time searching for the file.


2 Answers

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.

like image 101
David Morales Avatar answered Sep 17 '22 17:09

David Morales


Simply do as follows:

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

Documentation here.

like image 38
apneadiving Avatar answered Sep 18 '22 17:09

apneadiving