Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having a dot in the id of rails routes

I am working on Rails 2.3.11. If I have a url like http://www.abc.com/users/e.f.json , I expect the id to be 'e.f' and the expected format to be 'json'. Can someone please suggest a way to do it. Thank you!

like image 903
Satyaanveshi Avatar asked Aug 02 '11 06:08

Satyaanveshi


2 Answers

Because of the :format convention, Rails will parse all parameters without any dots. You can have route parameters with dots if you want:

# You can change the regex to more restrictive patterns
map.connect 'users/:id', :controller => 'users', :action => 'show', :id => /.*/

But since both '*' and '+' regex wildcards are greedy, it will ignore the (.:format) param completely.

Now, if you absolutely need to have dots in the username, there is a pseudo-workaround that could help you:

map.connect 'users/:id:format', :controller => 'users', :action => 'show', :requirements => { :format => /\.[^.]+/, :id => /.*/ }
map.connect 'users/:id', :controller => 'users', :action => 'show'

The downside is that you have to include the dot in the :format regex, otherwise it would be caught by the username expression. Then you have to handle the dotted format (e.g.: .json) in your controller.

like image 153
andersonvom Avatar answered Sep 30 '22 15:09

andersonvom


Here is a solution similar to andersonvom's, but keeps it all in one rule (and uses some modern Rails routing abbreviations).

map.connect 'users/:id(.:format)', to: 'users#show', id: /.*?/, format: /[^.]+/

(Note the . in front of :format)

The trick is to add an optional format, (.:format) and make the id regex non-greedy so the format is recognised. Keeping it in one rule is important if you want to give the route a name, so that you can use it for redirects, links, etc in a format-agnostic way.

like image 34
mahemoff Avatar answered Sep 30 '22 15:09

mahemoff