- 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
A Note on Route Order
Routes are consulted, both for recognition and for generation, in the order they are defined in routes.rb. The search for a match ends when the first match is found, which means that you have to watch out for false positives.
For example, let's say you have these two routes in your routes.rb:
map.connect "users/help", :controller => "users" map.connect ":controller/help", :controller => "main"
The logic here is that if someone connects to /users/help, there's a users/help action to help them. But if they connect to /any_other_controller/help, they get the help action of the main controller. Yes, it's tricky.
Now, consider what would happen if you reversed the order of these two routes:
map.connect ":controller/help", :controller => "main" map.connect "users/help", :controller => "users"
If someone connects to /users/help, that first route is going to match—because the more specific case, handling users differently, is defined later in the file.
It's very similar to other kinds of matching operations, like case statements:
case string when /./ puts "Matched any character!" when /x/ puts "Matched 'x'!" end
The second when will never be reached, because the first one will match 'x'. You always want to go from the specific or special cases, to the general case:
case string when /x/ puts "Matched 'x'!" when /./ puts "Matched any character!" end
These case examples use regular expressions—/x/ and so forth—to embody patterns against which a string can be tested for a match. Regular expressions actually play a role in the routing syntax too.