Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Bound Parameters

If we're speaking about route recognition, the bound parameters—key/value pairs in the hash of options at the end of the route's argument list—determine what's going to happen if and when this route matches an incoming URL. Let's say someone requests this URL from their web browser:

http://localhost:3000/myrecipes/apples

This URL will match the ingredient route. The result will be that the show action of the recipes controller will be executed. To see why, look at the route again:

map.connect 'myrecipes/:ingredient',
            :controller => "recipes",
            :action => "show"

The :controller and :action keys are bound: This route, when matched by a URL, will always take the visitor to exactly that controller and that action. You'll see techniques for matching controller and action based on wildcard matching shortly. In this example, though, there's no wildcard involved. The controller and action are hard-coded.

Now, when you're generating a URL for use in your code, you provide values for all the necessary bound parameters. That way, the routing system can do enough match-ups to find the route you want. (In fact, Rails will complain by raising an exception if you don't supply enough values to satisfy a route.)

The parameters are usually bundled in a hash. For example, to generate a URL from the ingredient route, you'd do something like this:

<%= link_to "Recipe for apples",
   :controller => "recipes",
   :action     => "show",
   :ingredient => "apples" %>

The values "recipes" and "show" for :controller and :action will match the ingredient route, which contains the same values for the same parameters. That means that the pattern string in that route will serve as the template—the blueprint—for the generated URL.

The use of a hash to specify URL components is common to all the methods that produce URLs (link_to, redirect_to, form_for, etc.). Underneath, these methods are making their own calls to url_for, a lower-level URL generation method that we'll talk about more a little further on.

We've left :ingredient hanging. It's a wildcard component of the pattern string.

  • + Share This
  • 🔖 Save To Your Account