Having a dot in the id of rails routes
Asked Answered
F

2

10

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!

Fernery answered 2/8, 2011 at 6:19 Comment(2)
I'm not familiar with the route syntax in 2.3, but you can try adding a constraint to the format to disallow periods. This should help keep the format to only the last dot-separated segment, but if you leave off the format you are going to wind up with part of your ID being used as the format.Project
possible duplicate of Rails — Params with "dot" (e.g. /google.com)Abner
R
13

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.

Renin answered 26/8, 2011 at 23:32 Comment(0)
M
4

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.

Marola answered 3/2, 2016 at 10:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.