Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Open Source

Rails Routing


The Default Route

If you look at the very bottom of routes.rb you'll see the default route:


map.connect ':controller/:action/:id'

The default route is, in a sense, the end of the journey; it defines what happens when nothing else happens. However, it's also a good place to start. If you understand the default route, you'll be able to apply that understanding to the more intricate examples as they arise.

Default Route Recognition

The default route consists of just a pattern string, containing three wildcard "receptors." Two of the receptors are the magic :controller and :action. That means this route determines what it's going to do based entirely on wildcards; there are no bound parameters, no hard-coded controller or action.

Here's a sample scenario. A request comes in with the URL:


http://localhost:3000/auctions/show/1

Let's say it doesn't match any other pattern. It hits the last route in the file -- the default route. There's definitely a congruency, a match. We've got a route with three receptors, and a URL with three values, and therefore, three positional matches:


:controller/:action/:id
   auctions / show / 1

We end up, then, with the auctions controller, the show action, and 1 for the id value (to be stored in params[:id]). The dispatcher now knows what to do. The behavior of the default route illustrates some of the specific default behaviors of the routing system. The default action for any request, for example, is index. And given a wildcard such as :id in the pattern string, the routing system prefers to find a value for it, but will go ahead and assign it nil rather than give up and conclude that there's no match. Table 1 shows some examples of URLs and how they will map to this rule, and with what results.

Table 1: Sample URLs and Their Routing

(The nil in the last case is probably an error because a show action with no id is usually not what you'd want!)

Spotlight on the :id Field

Note that the treatment of the :id field in the URL is not magic; it's just treated as a value with a name. If you wanted to, you could change the rule so that :id was :blah -- but then you'd have to remember to do


@auction = Auction.find(params[:blah])

in your controller action. The name :id is simply a convention. It reflects the commonness of the case where a given action needs access to a particular database record. The main business of the router is to determine the controller and action that will be executed. The id field is a bit of an extra; it's an opportunity for actions to hand a data field off to each other. The id field ends up in the params hash, which is automatically available to your controller actions. In the common, classic case, you'd use the value provided to dig a record out of the database:


class ItemsController < ApplicationController
  def show
    @item = Item.find(params[:id])
  end
end

In addition to providing the basis for recognizing URLs and triggering the correct behavior, the default route also plays a role in URL generation. Here's a link_to call that will use the default route to generate a URL similar to the one we submitted for recognition in the previous example:


<%= link_to item.description,
   :controller => "item",
   :action => "show",
   :id => item.id %>

This code presupposes a local variable called item, containing (we assume) an Item object. The idea is to create a hyperlink to the show action for the item controller, and to include a "drill-down" to the id of this particular item. The hyperlink, in other words, will look something like this:


<a href="localhost:3000/item/show/3"> A signed picture of Houdini</a>

This URL gets created courtesy of the route generation mechanism. Look again at the default route:


map.connect ':controller/:action/:id'

In our link_to call, we've provided values for all three of the fields in the pattern. All that the routing system has to do is plug in those values:


item/show/3

and insert the result into the URL. When someone clicks on the link, that URL will be recognized -- courtesy of the other half of the routing system, the recognition facility -- and the correct controller and action will be executed, with params[:id] set to 3.

The generation of the URL, in this example, uses wildcard logic: We've supplied three symbols, :controller, :action, and :id, in our pattern string, and those symbols will be replaced, in the generated URL, by whatever values we supply. Contrast this with our earlier example:


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

To cause the URL generator to select this route as its blueprint, you have to specify the exact words "recipes" and "show" for :controller and :action in the parameters you supply to link_to. In the case of the default route -- and, indeed, any route that has symbols embedded in its pattern -- you still have to match, but you can use any value.

Modifying the Default Route

A good way to get a feel for the routing system is to change things and see what happens. We'll do this with the default route. You'll probably want to change it back, but changing it will show you something about how routing works.

Specifically, swap :controller and :action in the pattern string:


# Install the default route as the lowest priority.
map.connect ':action/:controller/:id'

You've now set the default route to have actions first. That means that where you might previously have connected to http://localhost:3000/auctions/show/3, you'll now need to connect to http://localhost:3000/show/auctions/3. And when you generate a URL from this route, it will come out in the /show/auctions/3 order.

It's not particularly logical; the original default (the "default" default) route is better. But it shows you a bit of what's going on, specifically with the magic symbols :controller and :action. Try a few more changes and see what effect they have. (And then put it back the way it was!)


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.