1.13. Routing

The routing module provides URL rewriting in native Ruby. It’s a way to redirect incoming requests to controllers and actions. This replaces mod_rewrite rules. Best of all, Rails’s Routing works with any web server. Routes are defined in routes.rb in your RAILS_ROOT/config directory.

Figure 1-4. Honey-do task list screenshot

1.13.1. Routing Basics

Consider the following route, installed by Rails when you generate your application:

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

This route states that it expects requests to consist of a :controller followed by an :action that in turn is fed some :id.

Suppose you get an incoming request for /blog/edit/22. You’ll end up with:

params = { :controller => 'blog',
           :action     => 'edit',
           :id         => '22'     }

Think of creating routes as drawing a map for your requests. The map tells them where to go based on some predefined pattern:

ActionController::Routing::Routes.draw do |map|
  Pattern 1 tells some request to go to one place
  Pattern 2 tell them to go to another

The following symbols are special:


Maps to your controller name


Maps to an action with your controllers

Other names simply map to a parameter, as in the case of :id. Route priority

Routes are prioritized from top to bottom. The last route in that file is the lowest priority and will be applied last. If no route matches, 404 is returned.

Within blocks, the empty pattern ...

Get Rails Pocket Reference now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.