- 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 Your Own "Receptors"
So far, we've used the two magic parameters, :controller and :action, and the nonmagic but standard :id. It is also possible to use your own parameters, either hard-coded or wildcard. Doing this can help you add some expressiveness and self-documentation to your routes, as well as to your application code.
The main reason you'd want to use your own parameters is so that you can use them as handles in your code. For example, you might want a controller action to look like this:
def show @auction = Auction.find(params[:id]) @user = User.find(params[:user_id]) end
Here we've got the symbol :user_id showing up, along with :id, as a key to the params hash. That means it got there, somehow. In fact, it got there the same way as the :id parameter: It appears in the pattern for the route by which we got to the show action in the first place.
Here's that route:
map.connect 'auctions/:user_id/:id', :controller => "auctions", :action => "show"
This route, when faced with a URL like this
/auctions/3/1
will cause the auctions/show action to run, and will set both :user_id and :id in the params hash. (:user_id matches 3 positionally, and :id matches 1.)
On the URL generation side, all you have to do is include a :user_id key in your URL specs:
<%= link_to "Auction", :controller => "auctions", :action => "show", :user_id => current_user.id, :id => ts.id %>
The :user_id key in the hash will match the :user_id receptor in the route pattern. The :id key will also match, and so will the :controller and :action parameters. The result will be a URL based on the blueprint 'auctions/:user_id/:id'.
You can actually arbitrarily add many specifiers to a URL hash in calls to link_to and other similar methods. Any parameters you define that aren't found in a routing rule will be added to the URL as a query string. For example, if you add:
:some_other_thing => "blah"
to the hash in the link_to example above, you'll end up with this as your URL:
http://localhost:3000/auctions/3/1?some_other_thing=blah