Point in rail track identifier

I am working on Rails 2.3.11. If I have a url like http://www.abc.com/users/efjson , I expect the id to be "ef" and the expected format will be "json". Can someone suggest a way to do this. Thanks!

+7
source share
2 answers

Due to format convention: Rails will parse all parameters without any dots. You can route parameters with points if you want:

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

But since the "*" and "+" characters of regular expressions are greedy, it completely ignores the parameter (.: Format).

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

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

The disadvantage is that you must include the period in the regular expression: format, otherwise it will be caught by the username expression. Then you need to process the dot format (e.g...json) in your controller.

+8
source

Here is a solution similar to andersonvom's, but saves everything in one rule (and uses some modern Rails shortcut routing).

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

(Pay attention to . Before :format )

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

+2
source

All Articles