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!
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.
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.
精彩评论