- 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
Wildcard Components ("Receptors")
The symbol :ingredient inside the quoted pattern in the route is a wildcard parameter (or variable). You can think of it as a receptor: Its job is to be latched onto by a value. Which value latches onto which wildcard is determined positionally, lining the URL up with the pattern string:
http://localhost:3000/myrecipes/apples |
Someone connects to this URL... |
'myrecipes/:ingredient' |
which matches this pattern string |
The :ingredient receptor, in this example, receives the value apples from the URL. What that means for you is that the value params[:ingredient] will be set to the string "apples". You can access that value inside your recipes/show action. When you generate a URL, you have to supply values that will attach to the receptors—the wildcard symbols inside the pattern string. You do this using key => value syntax. That's the meaning of the last line in the preceding example:
<%= link_to "My Apple Recipes", :controller => "recipes", :action => "show", :ingredient => "apples" %>
In this call to link_to, we've provided values for three parameters. Two of them are going to match hard-coded, bound parameters in the route; the third, :ingredient, will be assigned to the slot in the URL corresponding to the :ingredient slot in the pattern string.
But they're all just hash key/value pairs. The call to link_to doesn't "know" whether it's supplying hard-coded or wildcard values. It just knows (or hopes!) that these three values, tied to these three keys, will suffice to pinpoint a route—and therefore a pattern string, and therefore a blueprint for a URL.