- The Two Purposes of Routing
- Bound Parameters
- Wildcard Components ("Receptors")
- Static Strings
- The routes.rb File
- The Ante-Default Route and respond_to
- The Empty Route
- Writing Custom Routes
- Using Static Strings
- Using Your Own "Receptors"
- A Note on Route Order
- Using Regular Expressions in Routes
- Default Parameters and the url_for Method
- Using Literal URLs
- Route Globbing
- Globbing Key-Value Pairs
- Named Routes
- What to Name Your Routes
- The Special Scope Method with_options
- Conclusion
Using Regular Expressions in Routes
Sometimes you want not only to recognize a route, but to recognize it at a finer-grained level than just what components or fields it has. You can do this through the use of regular expressions.1
For example, you could route all "show" requests so that they went to an error action if their id fields were non-numerical. You'd do this by creating two routes, one that handled numerical ids, and a fall-through route that handled the rest:
map.connect ':controller/show/:id', :id => /\d+/, :action => "show" map.connect ':controller/show/:id', :action => "alt_show"
If you want to do so, mainly for clarity, you can wrap your regular expression-based constraints in a special hash parameter named :requirements, like this:
map.connect ':controller/show/:id', :action => "show", :requirements => { :id => /\d+/ }
Regular expressions in routes can be useful, especially when you have routes that differ from each other only with respect to the patterns of their components. But they're not a full-blown substitute for data-integrity checking. A URL that matches a route with regular expressions is like a job candidate who's passed a first interview. You still want to make sure that the values you're dealing with are usable and appropriate for your application's domain.