Question

I want to have SEO optimized urls like this

http://example.com/sites/1-blau.de/plans

But the dot in the path cause Rails to chock. How do I escape dots to percentage notation form so it can work?

My routes:

resources :sites, only: [] do
  resources :plans, only: [:index, :show] do
  end
end

I have tried URI.escape and CGI.escape, neither worked.

URI.escape('a.b')=> "a.b"
CGI.escape('a.b')=> "a.b"

What I thought I wanted

Foo.escape('a.b')=> "a%2Eb"
Was it helpful?

Solution

Use a constraint that accepts dot character.

get 'sites/:site_name/plans', constraints: { site_name: /[a-zA-Z0-9\.]+/ }

From the doc:

By default, dynamic segments don't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within a dynamic segment, add a constraint that overrides this – for example, id: /[^/]+/ allows anything except a slash.

OTHER TIPS

Note that the accepted answer (adding a constraint that allows dots) unfortunately breaks your format. For example, if you want to support both http://example.com/sites/1-blau.de and http://example.com/sites/1-blau.de.json, the second will not be handled by rails as format: json. The :site_name will be the entire 1-blau.de.json. Uri encoding the dot as %2E gets handled differently by different browsers (Chrome will resolve %2E as a '.' whereas Firefox will keep it as %2E).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top