The Rails routing system does two things: It recognizes URLs and it generates URLs.
Recognizing URLs is useful because it's how your application decides what it's supposed to do when a particular request comes in:
http://localhost:3000/recipes_for/apples <i>What do we do now?! </i>
Generating URLs is useful because it allows you to use relatively high-level syntax in your view templates and controllers when you need insert a URL -- so you don't have to do this:
<a href="http://localhost:3000/recipes_for/apples">Apple recipes</> <i>Not much fun having to type this out by hand!</i>
The routing system deals with both of these issues: how to interpret (recognize) a request URL and how to write (generate) a URL.
It performs both of these functions based on rules that you provide. The rules are inserted into the file config/routes.rb, using special syntax. (Actually it's just Ruby program code, but it uses special methods and parameters.)
Each rule -- or, to use the more common term, each route -- includes a pattern string, which will be used both as a template for matching URLs and as a blueprint for writing them. The pattern string contains a mixture of static substrings, forward slashes (it's mimicking URL syntax), and wildcard, positional parameters that serve as "receptors" for corresponding values in a URL, for both recognition and generation purposes.
A route can also include one or more bound parameters, in the form of key/value pairs in a hash.
The fate of these key/value pairs depends on what the key is. A couple of keys (:controller and :action) are "magic," and they determine what's actually going to happen. Other keys (:blah, :whatever, etc.) are stashed in CGI space for future reference. Putting some flesh on the bones of this description, here's a sample route, related to the preceding examples:
map.connect 'recipes_for/:ingredient', :controller => "recipes", :action => "show"
In this example, you can see:
- A static string (recipes_for)
- A wildcard URL component (:ingredient)
- Bound parameters (:controller, :action)
Routes have a pretty rich syntax -- this one isn't by any means the most complex (nor the simplest) -- because they have to do so much. A single route, such as the preceding one, has to provide enough information both to match an existing URL and to manufacture a new one. The route syntax is engineered to address both of these processes. It's actually not hard to grasp, if you take each type of field in turn. We'll do a run-through using the "ingredient" route. Don't worry if it all doesn't sink in the first time through. We'll be unpacking and expanding on the techniques and details throughout the section. As we go through the route anatomy, we'll look at the role of each part in both URL recognition and URL generation. Keep in mind that this is just an introductory example. You can do lots of different things with routes; but examining this example will give you a good start in seeing how it all works.