Skip to content

Latest commit

 

History

History
800 lines (536 loc) · 29.4 KB

routing.textile

File metadata and controls

800 lines (536 loc) · 29.4 KB

Rails Routing from the Outside In

This guide covers the user-facing features of Rails routing. By referring to this guide, you will be able to:

  • Understand the code in routes.rb
  • Construct your own routes, using either the preferred resourceful style or with the match method
  • Identify what parameters to expect an action to receive
  • Automatically create URLs using route helpers
  • Use advanced techniques such as constraints and Rack endpoints

endprologue.

The Purpose of the Rails Router

The Rails router recognizes URLs and dispatches them to a controller’s action. It can also generate URLs, avoiding the need to hardcode URL strings in your views.

Connecting URLs to Code

When your Rails application receives an incoming request

GET /patients/17

it asks the router to match it to a controller action. If the first matching route is

match “/patients/:id” => “patients#show”

the request is dispatched to the patients controller’s show action with { :id => “17” } in params.

Generating URLs from Code

You can also generate routes. If your application contains this code:

@patient = Patient.find(17)

<%= link_to “Patient Record”, patients_path(@patient.id) %>

The router will generate the path /patients/17. This reduces the brittleness of your view and makes your code easier to understand.

Resource Routing: the Rails Default

Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index, show, new, edit, create, update and destroy actions, a resourceful route declares them in a single line of code.

Resources on the Web

Browsers request pages from Rails by making a request for a URL using a specific HTTP method, such as GET, POST, PUT and DELETE. Each method is a request to perform an operation on the resource. A resource route maps a number of related request to the actions in a single controller.

When your Rails application receives an incoming request for

DELETE /photos/17

it asks the router to map it to a controller action. If the first matching route is

resources :photos

Rails would dispatch that request to the destroy method on the photos controller with { :id => “17” } in params.

CRUD, Verbs, and Actions

In Rails, a resourceful route provides a mapping between HTTP verbs and URLs and controller actions. By convention, each action also maps to particular CRUD operations in a database. A single entry in the routing file, such as

resources :photos

creates seven different routes in your application, all mapping to the Photos controller:

Verb URL action used for
GET /photos index display a list of all photos
GET /photos/new new return an HTML form for creating a new photo
POST /photos create create a new photo
GET /photos/:id show display a specific photo
GET /photos/:id/edit edit return an HTML form for editing a photo
PUT /photos/:id update update a specific photo
DELETE /photos/:id destroy delete a specific photo

URLs and Paths

Creating a resourceful route will also expose a number of helpers to the controllers in your application. In the case of resources :photos:

  • photos_path returns /photos
  • new_photo_path returns /photos/new
  • edit_photo_path returns /photos/edit
  • photo_path(id) returns /photos/:id (for instance, photo_path(10) returns /photos/10)

Each of these helpers has a corresponding _url helper (such as photos_url) which returns the same path prefixed with the current host, port and path prefix.

NOTE: Because the router uses the HTTP verb and URL to match inbound requests, four URLs map to seven different actions.

Defining Multiple Resources at the Same Time

If you need to create routes for more than one resource, you can save a bit of typing by defining them all with a single call to resources:

resources :photos, :books, :videos

This works exactly the same as

resources :photos
resources :books
resources :videos

Singular Resources

Sometimes, you have a resource that clients always look up without referencing an ID. A common example, /profile always shows the profile of the currently logged in user. In this case, you can use a singular resource to map /profile (rather than /profile/:id) to the show action.

match “profile” => “users#show”

This resourceful route

resource :geocoder

creates six different routes in your application, all mapping to the Geocoders controller:

Verb URL action used for
GET /geocoder/new new return an HTML form for creating the geocoder
POST /geocoder create create the new geocoder
GET /geocoder show display the one and only geocoder resource
GET /geocoder/edit edit return an HTML form for editing the geocoder
PUT /geocoder update update the one and only geocoder resource
DELETE /geocoder destroy delete the geocoder resource

NOTE: Because you might want to use the same controller for a singular route (/account) and a plural route (/accounts/45), singular resources map to plural controllers.

A singular resourceful route generates these helpers:

  • new_geocoder_path returns /geocoder/new
  • edit_geocoder_path returns /geocoder/edit
  • geocoder_path returns /geocoder

As with plural resources, the same helpers ending in _url will also include the host, port and path prefix.

Controller Namespaces and Routing

You may wish to organize groups of controllers under a namespace. Most commonly, you might group a number of administrative controllers under an Admin:: namespace. You would place these controllers under the app/controllers/admin directory, and you can group them together in your router:

namespace “admin” do
resources :posts, :comments
end

This will create a number of routes for each of the posts and comments controller. For Admin::PostsController, Rails will create:

Verb URL action helper
GET /admin/photos index admin_photos_path
GET /admin/photos/new new new_admin_photos_path
POST /admin/photos create admin_photos_path
GET /admin/photos/1 show admin_photo_path(id)
GET /admin/photos/1/edit edit edit_admin_photo_path(id)
PUT /admin/photos/1 update admin_photo_path(id)
DELETE /admin/photos/1 destroy admin_photo_path(id)

If you want to route /photos (without the prefix /admin) to Admin::PostsController, you could use

scope :module => “admin” do
resources :posts, :comments
end

or, for a single case

resources :posts, :module => “admin”

If you want to route /admin/photos to PostsController (without the Admin:: module prefix), you could use

scope “/admin” do
resources :posts, :comments
end

or, for a single case

resources :posts, :path => “/admin”

In each of these cases, the named routes remain the same as if you did not use scope. In the last case, the following URLs map to PostsController:

Verb URL action helper
GET photos index photos_path
GET photos/new new photos_path
POST photos create photos_path
GET photos/1 show photo_path(id)
GET photos/1/edit edit dmin_photo_path(id)
PUT photos/1 update photo_path(id)
DELETE photos/1 destroy photo_path(id)

Nested Resources

It’s common to have resources that are logically children of other resources. For example, suppose your application includes these models:

class Magazine < ActiveRecord::Base
has_many :ads
end

class Ad < ActiveRecord::Base
belongs_to :magazine
end

Nested routes allow you to capture this relationship in your routing. In this case, you could include this route declaration:

resources :magazines do
resources :ads
end

In addition to the routes for magazines, this declaration will also route ads to an AdsController. The ad URLs require a magazine:

Verb URL action used for
GET /magazines/1/ads index display a list of all ads for a specific magazine
GET /magazines/1/ads/new new return an HTML form for creating a new ad belonging to a specific magazine
POST /magazines/1/ads create create a new ad belonging to a specific magazine
GET /magazines/1/ads/1 show display a specific ad belonging to a specific magazine
GET /magazines/1/ads/1/edit edit return an HTML form for editing an ad belonging to a specific magazine
PUT /magazines/1/ads/1 update update a specific ad belonging to a specific magazine
DELETE /magazines/1/ads/1 destroy delete a specific ad belonging to a specific magazine

This will also create routing helpers such as magazine_ads_url and edit_magazine_ad_path. These helpers take an instance of Magazine as the first parameter (magazine_ads_url(@magazine)).

Limits to Nesting

You can nest resources within other nested resources if you like. For example:

resources :publishers do
resources :magazines do
resources :photos
end
end

Deeply-nested resources quickly become cumbersome. In this case, for example, the application would recognize URLs such as

/publishers/1/magazines/2/photos/3

The corresponding route helper would be publisher_magazine_photo_url, requiring you to specify objects at all three levels. Indeed, this situation is confusing enough that a popular article by Jamis Buck proposes a rule of thumb for good Rails design:

TIP: Resources should never be nested more than 1 level deep.

Creating URLs From Objects

In addition to using the routing helpers, Rails can also create URLs from an array of parameters. For example, suppose you have this set of routes:

resources :magazines do
resources :ads
end

When using magazine_ad_path, you can pass in instances of Magazine and Ad instead of the numeric IDs.

<%= link_to “Ad details”, magazine_ad_path(@magazine, @ad) %>

You can also use url_for with a set of objects, and Rails will automatically determine which route you want:

<%= link_to “Ad details”, url_for(@magazine, @ad) %>

In this case, Rails will see that @magazine is a Magazine and @ad is an Ad and will therefore use the magazine_ad_path helper. In helpers like link_to, you can specify just the object in place of the full url_for call:

<%= link_to “Ad details”, [@magazine, @ad] %>

If you wanted to link to just a magazine, you could leave out the Array:

<%= link_to “Magazine details”, @magazine %>

This allows you to treat instances of your models as URLs, and is a key advantage to using the resourceful style.

Adding More RESTful Actions

You are not limited to the seven routes that RESTful routing creates by default. If you like, you may add additional routes that apply to the collection or individual members of the collection.

Adding Member Routes

To add a member route, just add member block into resource block:

resources :photos do
member do
get :preview
end
end

This will recognize /photos/1/preview with GET, and route to the preview action of PhotosController. It will also create the preview_photo_url and preview_photo_path helpers.

Within the block of member routes, each route name specifies the HTTP verb that it will recognize. You can use get, put, post, or delete here. If you don’t have multiple member routes, you can also passing :on to a route.

resources :photos do
get :preview, :on => :member
end

Adding Collection Routes

To add a route to the collection:

resources :photos do
collection do
get :search
end
end

This will enable Rails to recognize URLs such as /photos/search with GET, and route to the search action of PhotosController. It will also create the search_photos_url and search_photos_path route helpers.

Just as with member routes, you can pass :on to a route.

resources :photos do
get :search, :on => :collection
end

A Note of Caution

If you find yourself adding many extra actions to a resourceful route, it’s time to stop and ask yourself whether you’re disguising the presence of another resource.

Non-Resourceful Routes

In addition to resource routing, Rails has powerful support for routing arbitrary URLs to actions. Here, you don’t get groups of routes automatically generated by resourceful routing. Instead, you set up each route within your application separately.

While you should usually use resourceful routing, there are still many places where the simpler routing is more appropriate. There’s no need to try to shoehorn every last piece of your application into a resourceful framework if that’s not a good fit.

In particular, simple routing makes it very easy to map legacy URLs to new Rails actions.

Bound Parameters

When you set up a regular route, you supply a series of symbols that Rails maps to parts of an incoming HTTP request. Two of these symbols are special: :controller maps to the name of a controller in your application, and :action maps to the name of an action within that controller. For example, consider one of the default Rails routes:

match ‘:controller(/:action(/:id))’

If an incoming request of /photos/show/1 is processed by this route (because it hasn’t matched any previous route in the file), then the result will be to invoke the show action of the PhotosController, and to make the final parameter “1” available as params[:id]. This route will also route the incoming request of /photos to PhotosController, since :action and :id are optional parameters, denoted by parentheses.

Dynamic Segments

You can set up as many dynamic segments within a regular route as you like. Anything other than :controller or :action will be available to the action as part of params. If you set up this route:

match ‘:controller/:action/:id/:user_id’

An incoming URL of /photos/show/1/2 will be dispatched to the show action of the PhotosController. params[:id] will be “1”, and params[:user_id] will be “2”.

Static Segments

You can specify static segments when creating a route.

match ‘:controller/:action/:id/with_user/:user_id’

This route would respond to URLs such as /photos/show/1/with_user/2. In this case, params would be { :controller => “photos”, :action => “show”, :id => “1”, :user_id => “2” }.

The Query String

The params will also include any parameters from the query string. For example, with this route:

match ‘:controller/:action/:id’

An incoming URL of /photos/show/1?user_id=2 will be dispatched to the show action of the Photos controller. params will be { :controller => “photos”, :action => “show”, :id => “1”, :user_id => “2” }.

Defining Defaults

You do not need to explicitly use the :controller and :action symbols within a route. You can supply them as defaults:

match ‘photos/:id’ => ‘photos#show’

With this route, Rails will match an incoming URL of /photos/12 to the show action of PhotosController.

You can also define other defaults in a route by supplying a hash for the :defaults option. This even applies to parameters that you do not specify as dynamic segments. For example:

match ‘photos/:id’ => ‘photos#show’, :defaults => { :format => ‘jpg’ }

Rails would match photos/12 to the show action of PhotosController, and set params[:format] to “jpg”.

Naming Routes

You can specify a name for any route using the :as option.

match ‘exit’ => ‘sessions#destroy’, :as => :logout

This will create logout_path and logout_url as named helpers in your application. Calling logout_path will return /logout

Segment Constraints

You can use the :constraints option to enforce a format for a dynamic segment:

match ‘photo/:id’ => ‘photos#show’, :constraints => { :id => /[A-Z]\d{5}/ }

This route would match URLs such as /photo/A12345. You can more succinctly express the same route this way:

match ‘photo/:id’ => ‘photos#show’, :id => /[A-Z]\d{5}/

Request-Based Constraints

You can also constrain a route based on any method on the Request object that returns a String.

You specify a request-based constraint the same way that you specify a segment constraint:

match “photo”, :constraints => {:subdomain => "admin"}

You can also specify constrains in a block form:

namespace “admin” do
constraints :subdomain => “admin” do
resources :photos
end
end

Advanced Constraints

If you have a more advanced constraint, you can provide an object that responds to matches? that Rails should use. Let’s say you wanted to route all users on a blacklist to the BlacklistController. You could do:

class BlacklistConstraint
def initialize
@ips = Blacklist.retrieve_ips
end

def matches?(request) @ips.include?(request.remote_ip) end

end

TwitterClone::Application.routes.draw do
match “*path” => “blacklist#index”,
:constraints => BlacklistConstraint.new
end

Route Globbing

Route globbing is a way to specify that a particular parameter should be matched to all the remaining parts of a route. For example

match ‘photo/*other’ => ‘photos#unknown’

This route would match photo/12 or /photo/long/path/to/12, setting params[:other] to “12” or “long/path/to/12”.

Redirection

You can redirect any path to another path using the redirect helper in your router:

match “/stories” => redirect(“/posts”)

You can also reuse dynamic segments from the match in the path to redirect to:

match “/stories/:name” => redirect(“/posts/%{name}”)

You can also provide a block to redirect, which receives the params and (optionally) the request object:

match “/stories/:name” => redirect {|params| “/posts/#{params[:name].pluralize}” }
match “/stories” => redirect {|p, req| “/posts/#{req.subdomain}” }

In all of these cases, if you don’t provide the leading host (http://www.example.com), Rails will take those details from the current request.

Routing to Rack Applications

Instead of a String, like “posts#index”, which corresponds to the index action in the PostsController, you can specify any Rack application as the endpoint for a matcher.

match “/application.js” => Sprockets

As long as Sprockets responds to call and returns a [status, headers, body], the router won’t know the difference between the Rack application and an action.

NOTE: For the curious, “posts#index” actually expands out to PostsController.action(:index), which returns a valid Rack application.

Using root

You can specify what Rails should route “/” to with the root method:

root :to => ‘pages#main’

You should put the root route at the end of the file.

Customizing Resourceful Routes

While the default routes and helpers generated by resources :posts will usually serve you well, you may want to customize them in some way. Rails allows you to customize virtually any generic part of the resourceful helpers.

Specifying a Controller to Use

The :controller option lets you explicitly specify a controller to use for the resource. For example:

resources :photos, :controller => “images”

will recognize incoming URLs beginning with /photo but route to the Images controller:

Verb URL action
GET /photos index
GET /photos/new new
POST /photos create
GET /photos/1 show
GET /photos/1/edit edit
PUT /photos/1 update
DELETE /photos/1 destroy

NOTE: Use photos_path, new_photos_path, etc. to generate URLs for this resource.

Specifying Constraints

You can use the :constraints option to specify a required format on the implicit id. For example:

resources :photos, :constraints => {:id => /[A-Z][A-Z][0-9]+/}

This declaration constrains the :id parameter to match the supplied regular expression. So, in this case, the router would no longer match /photos/1 to this route. Instead, /photos/RR27 would match.

You can specify a single constraint to a apply to a number of routes by using the block form:

constraints(:id => /[A-Z][A-Z][0-9]+/) do
resources :photos
resources :accounts
end

NOTE: Of course, you can use the more advanced constraints available in non-resourceful routes in this context

Overriding the Named Helpers

The :as option lets you override the normal naming for the named route helpers. For example:

resources :photos, :as => “images”

will recognize incoming URLs beginning with /photos and route the requests to PhotosController:

HTTP verb URL action named helper
GET /photos index images_path
GET /photos/new new new_image_path
POST /photos create images_path
GET /photos/1 show image_path
GET /photos/1/edit edit edit_image_path
PUT /photos/1 update image_path
DELETE /photos/1 destroy image_path

Overriding the new and edit Segments

The :path_names option lets you override the automatically-generated “new” and “edit” segments in URLs:

resources :photos, :path_names => { :new => ‘make’, :edit => ‘change’ }

This would cause the routing to recognize URLs such as

/photos/make
/photos/1/change

NOTE: The actual action names aren’t changed by this option. The two URLs shown would still route to the new and edit actions.

TIP: If you find yourself wanting to change this option uniformly for all of your routes, you can use a scope:

scope :path_names => { :new => “make” } do

  1. rest of your routes
    end

Overriding the Named Helper Prefix

You can use the :name_prefix option to add a prefix to the named route helpers that Rails generates for a route. You can use this option to prevent collisions between routes using a path scope.

scope “admin” do
resources :photos, :name_prefix => “admin”
end

resources :photos

This will provide route helpers such as admin_photos_path, new_admin_photo_path etc.

You could specify a name prefix to use for a group of routes in the scope:

scope “admin”, :name_prefix => “admin” do
resources :photos, :accounts
end

resources :photos, :accounts

NOTE: The namespace scope will automatically add a :name_prefix as well as :module and :path prefixes.

Restricting the Routes Created

By default, Rails creates routes for all seven of the default actions (index, show, new, create, edit, update, and destroy) for every RESTful route in your application. You can use the :only and :except options to fine-tune this behavior. The :only option tells Rails to create only the specified routes:

resources :photos, :only => [:index, :show]

Now, a GET request to /photos would succeed, but a POST request to /photos (which would ordinarily be routed to the create action) will fail.

The :except option specifies a route or list of routes that Rails should not create:

resources :photos, :except => :destroy

In this case, Rails will create all of the normal routes except the route for destroy (a DELETE request to /photos/:id).

TIP: If your application has many RESTful routes, using :only and :except to generate only the routes that you actually need can cut down on memory use and speed up the routing process.

Translated Paths

Using scope, we can alter path names generated by resources:

scope(:path_names => { :new => “neu”, :edit => “bearbeiten” }) do
resources :categories, :path => “kategorien”
end

Rails now creates routes to the CategoriesControlleR.

HTTP verb URL action
GET /kategorien index
GET /kategorien/neu new
POST /kategorien create
GET /kategorien/1 show
GET /kategorien/:id/bearbeiten edit
PUT /kategorien/1 update
DELETE /kategorien/1 destroy

Overriding the Singular Form

If you want to customize the singular name of the route in the named helpers, you can use the :singular option.

resources :teeth, :singular => “tooth”

TIP: If you want to define the singular form of a word for your entire application, you should add additional rules to the Inflector instead.

Using :name_prefix in Nested Resources

The :name_prefix option overrides the automatically-generated prefix for the parent resource in nested route helpers. For example,

resources :magazines do
resources :ads, :name_prefix => ‘periodical’
end

This will create routing helpers such as magazine_periodical_ads_url and edit_magazine_periodical_ad_path.

Inspecting and Testing Routes

Rails offers facilities for inspecting and testing your routes.

Seeing Existing Routes with rake

If you want a complete list of all of the available routes in your application, run rake routes command. This will print all of your routes, in the same order that they appear in routes.rb. For each route, you’ll see:

  • The route name (if any)
  • The HTTP verb used (if the route doesn’t respond to all verbs)
  • The URL pattern to match
  • The routing parameters for the route

For example, here’s a small section of the rake routes output for a RESTful route:

          users GET  /users          {:controller=>"users", :action=>"index"}
formatted_users GET  /users.:format  {:controller=>"users", :action=>"index"}
                POST /users          {:controller=>"users", :action=>"create"}
                POST /users.:format  {:controller=>"users", :action=>"create"}

TIP: You’ll find that the output from rake routes is much more readable if you widen your terminal window until the output lines don’t wrap.

Testing Routes

Routes should be included in your testing strategy (just like the rest of your application). Rails offers three built-in assertions designed to make testing routes simpler:

  • assert_generates
  • assert_recognizes
  • assert_routing
The assert_generates Assertion

Use assert_generates to assert that a particular set of options generate a particular path. You can use this with default routes or custom routes

assert_generates “/photos/1”, { :controller => “photos”, :action => “show”, :id => “1” }
assert_generates “/about”, :controller => “pages”, :action => “about”

The assert_recognizes Assertion

The assert_recognizes assertion is the inverse of assert_generates. It asserts that Rails recognizes the given path and routes it to a particular spot in your application.

assert_recognizes({ :controller => “photos”, :action => “show”, :id => “1” }, “/photos/1”)

You can supply a :method argument to specify the HTTP verb:

assert_recognizes({ :controller => “photos”, :action => “create” }, { :path => “photos”, :method => :post })

You can also use the resourceful helpers to test recognition of a RESTful route:

assert_recognizes new_photo_url, { :path => “photos”, :method => :post }

The assert_routing Assertion

The assert_routing assertion checks the route both ways: it tests that the path generates the options, and that the options generate the path. Thus, it combines the functions of assert_generates and assert_recognizes.

assert_routing({ :path => “photos”, :method => :post }, { :controller => “photos”, :action => “create” })

Changelog

Lighthouse ticket

  • April 10, 2010: Updated guide to remove outdated and superfluous information, and to provide information about new features, by Yehuda Katz
  • April 2, 2010: Updated guide to match new Routing DSL in Rails 3, by Rizwan Reza
  • Febuary 1, 2010: Modifies the routing documentation to match new routing DSL in Rails 3, by Prem Sichanugrist
  • October 4, 2008: Added additional detail on specifying verbs for resource member/collection routes, by Mike Gunderloy
  • September 23, 2008: Added section on namespaced controllers and routing, by Mike Gunderloy
  • September 10, 2008: initial version by Mike Gunderloy