v1.2.0 - Show latest stable - 3 notes


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' Routing works with any web server. Routes are defined in routes.rb in your RAILS_ROOT/config directory.

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 turns is fed by 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:

  :controller maps to your controller name
  :action     maps to an action with your controllers

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

Route priority

Not all routes are created equally. Routes have priority defined by the order of appearance of the routes in the routes.rb file. The priority goes from top to bottom. The last route in that file is at the lowest priority will be applied last. If no route matches, 404 is returned.

Within blocks, the empty pattern goes first i.e. is at the highest priority. In practice this works out nicely:

 ActionController::Routing::Routes.draw do |map|
   map.with_options :controller => 'blog' do |blog|
     blog.show    '',  :action => 'list'
   map.connect ':controller/:action/:view

In this case, invoking blog controller (with an URL like ’/blog/’) without parameters will activate the ‘list’ action by default.

Defaults routes and default parameters

Setting a default route is straightforward in Rails because by appending a Hash to the end of your mapping you can set default parameters.


 ActionController::Routing:Routes.draw do |map|
   map.connect ':controller/:action/:id', :controller => 'blog'

This sets up blog as the default controller if no other is specified. This means visiting ’/’ would invoke the blog controller.

More formally, you can define defaults in a route with the :defaults key.

  map.connect ':controller/:id/:action', :action => 'show', :defaults => { :page => 'Dashboard' }

Named routes

Routes can be named with the syntax map.name_of_route options, allowing for easy reference within your source as name_of_route_url.


  # In routes.rb
  map.login 'login', :controller => 'accounts', :action => 'login'

  # With render, redirect_to, tests, etc.
  redirect_to login_url

Arguments can be passed as well.

  redirect_to show_item_url(:id => 25)

When using with_options, the name goes after the item passed to the block.

 ActionController::Routing::Routes.draw do |map|
   map.with_options :controller => 'blog' do |blog|
     blog.show    '',            :action  => 'list'
     blog.delete  'delete/:id',  :action  => 'delete',
     blog.edit    'edit/:id',    :action  => 'edit'
   map.connect ':controller/:action/:view

You would then use the named routes in your views:

  link_to @article.title, show_url(:id => @article.id)

Pretty URL’s

Routes can generate pretty URLs. For example:

 map.connect 'articles/:year/:month/:day',
             :controller => 'articles',
             :action     => 'find_by_date',
             :year       => /\d{4}/,
             :month => /\d{1,2}/,
             :day   => /\d{1,2}/

 # Using the route above, the url below maps to:
 # params = {:year => '2005', :month => '11', :day => '06'}
 # http://localhost:3000/articles/2005/11/06

Regular Expressions and parameters

You can specify a reqular expression to define a format for a parameter.

 map.geocode 'geocode/:postalcode', :controller => 'geocode',
             :action => 'show', :postalcode => /\d{5}(-\d{4})?/

or more formally:

  map.geocode 'geocode/:postalcode', :controller => 'geocode',
                     :action => 'show',
                     :requirements { :postalcode => /\d{5}(-\d{4})?/ }

Route globbing

Specifying *[string] as part of a rule like :

 map.connect '*path' , :controller => 'blog' , :action => 'unrecognized?'

will glob all remaining parts of the route that were not recognized earlier. This idiom must appear at the end of the path. The globbed values are in params[:path] in this case.

Reloading routes

You can reload routes if you feel you must:


This will clear all named routes and reload routes.rb

Testing Routes

The two main methods for testing your routes:


 def test_movie_route_properly_splits
  opts = {:controller => "plugin", :action => "checkout", :id => "2"}
  assert_routing "plugin/checkout/2", opts

assert_routing lets you test whether or not the route properly resolves into options.


 def test_route_has_options
  opts = {:controller => "plugin", :action => "show", :id => "12"}
  assert_recognizes opts, "/plugins/show/12"

Note the subtle difference between the two: assert_routing tests that an URL fits options while assert_recognizes tests that an URL breaks into parameters properly.

In tests you can simply pass the URL or named route to get or post.

 def send_to_jail
   get '/jail'
   assert_response :success
   assert_template "jail/front"

 def goes_to_login
   get login_url


SEPARATORS = %w( / ; . , ? )

Routes = RouteSet.new


Show files where this module is defined (1 file)
Register or log in to add new notes.
November 11, 2008
4 thanks

:use_route to force named routes in url_for

If you are using a plugin or library that calls url_for internally, you can force it to use a particular named route with the :use_route key. For instance, calling:

url_for(:controller => 'posts', :action => 'view', :id => post, :use_route => :special_post)

will have the same effect as:


Naturally, this is much more verbose if you’re calling it directly, but can be a lifesaver if url_for is being called inside another method (e.g. will_paginate).

April 25, 2009
4 thanks

Set :use_route to nil to let Rails pick the best route

Imagine the following case. You have two landing pages, one generic one, and an account specific one. The urls are as follows:

map.landing 'landing', :controller => 'landing', :action => 'index'
map.account_landing 'accounts/:account_id/landing', :controller => 'landing', :action => 'index'

Now imagine you want a path to the landing page, using the most specific route possible. If you have an account_id, use it, if not, skip it.

You could do

url_for(:controller => 'landing', :action => 'index', :account_id => current_account)

If current_account is set you’ll get “/accounts/:account_id/landing” if not, you’ll get “/landing”. However, that just looks ugly.

Enter :use_route => nil.

landing_path(:account_id => nil)                    # => '/landing'
landing_path(:account_id => 1)                      # => '/landing?account_id=1'
landing_path(:account_id => nil, :use_route => nil) # => '/landing'
landing_path(:account_id => 1, :use_route => nil)   # => '/accounts/1/landing'

Setting :use_route to nil, is equivalent to the earlier #url_for example.

July 15, 2010 - (<= v2.3.8)
2 thanks