2012-09-01 17:25:58 -04:00
Rails Routing from the Outside In
=================================
2009-02-05 20:57:02 -05:00
2012-11-29 17:25:02 -05:00
This guide covers the user-facing features of Rails routing.
After reading this guide, you will know:
2009-02-05 20:57:02 -05:00
2012-12-07 12:50:09 -05:00
* How to interpret the code in `routes.rb` .
* How to construct your own routes, using either the preferred resourceful style or the `match` method.
* What parameters to expect an action to receive.
* How to automatically create paths and URLs using route helpers.
* Advanced techniques such as constraints and Rack endpoints.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
--------------------------------------------------------------------------------
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
The Purpose of the Rails Router
-------------------------------
2009-02-05 20:57:02 -05:00
2010-07-21 18:32:39 -04:00
The Rails router recognizes URLs and dispatches them to a controller's action. It can also generate paths and URLs, avoiding the need to hardcode strings in your views.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Connecting URLs to Code
2009-02-05 20:57:02 -05:00
2012-12-02 15:52:12 -05:00
When your Rails application receives an incoming request for:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
GET /patients/17
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-12-02 15:52:12 -05:00
it asks the router to match it to a controller action. If the first matching route is:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
get '/patients/:id', to: 'patients#show'
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-11-08 00:36:50 -05:00
the request is dispatched to the `patients` controller's `show` action with `{ id: '17' }` in `params` .
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Generating Paths and URLs from Code
2010-01-31 23:50:44 -05:00
2013-05-28 08:34:47 -04:00
You can also generate paths and URLs. If the route above is modified to be:
2012-06-24 11:01:46 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
get '/patients/:id', to: 'patients#show', as: 'patient'
2012-09-01 17:08:06 -04:00
```
2012-06-24 11:01:46 -04:00
2012-12-02 15:52:12 -05:00
and your application contains this code in the controller:
2010-01-31 23:50:44 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2010-04-10 04:51:41 -04:00
@patient = Patient.find(17)
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-12-02 15:52:12 -05:00
and this in the corresponding view:
2012-12-02 15:11:26 -05:00
2012-09-01 17:08:06 -04:00
```erb
2012-11-08 00:36:50 -05:00
< %= link_to 'Patient Record', patient_path(@patient) %>
2012-09-01 17:08:06 -04:00
```
2010-01-31 23:50:44 -05:00
2012-12-02 15:11:26 -05:00
then the router will generate the path `/patients/17` . This reduces the brittleness of your view and makes your code easier to understand. Note that the id does not need to be specified in the route helper.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
Resource Routing: the Rails Default
-----------------------------------
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
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.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Resources on the Web
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
Browsers request pages from Rails by making a request for a URL using a specific HTTP method, such as `GET` , `POST` , `PATCH` , `PUT` and `DELETE` . Each method is a request to perform an operation on the resource. A resource route maps a number of related requests to actions in a single controller.
2009-02-05 20:57:02 -05:00
2012-12-02 15:52:12 -05:00
When your Rails application receives an incoming request for:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```
2010-04-10 04:51:41 -04:00
DELETE /photos/17
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-12-02 15:52:12 -05:00
it asks the router to map it to a controller action. If the first matching route is:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2010-04-10 04:51:41 -04:00
resources :photos
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-11-08 00:36:50 -05:00
Rails would dispatch that request to the `destroy` method on the `photos` controller with `{ id: '17' }` in `params` .
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### CRUD, Verbs, and Actions
2009-02-05 20:57:02 -05:00
2012-12-02 15:52:12 -05:00
In Rails, a resourceful route provides a mapping between HTTP verbs and URLs to controller actions. By convention, each action also maps to particular CRUD operations in a database. A single entry in the routing file, such as:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2010-01-31 23:50:44 -05:00
resources :photos
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
creates seven different routes in your application, all mapping to the `Photos` controller:
2009-02-05 20:57:02 -05:00
2013-10-31 06:45:09 -04:00
| HTTP Verb | Path | Controller#Action | Used for |
| --------- | ---------------- | ----------------- | -------------------------------------------- |
| GET | /photos | photos#index | display a list of all photos |
| GET | /photos/new | photos#new | return an HTML form for creating a new photo |
| POST | /photos | photos#create | create a new photo |
| GET | /photos/:id | photos#show | display a specific photo |
| GET | /photos/:id/edit | photos#edit | return an HTML form for editing a photo |
| PATCH/PUT | /photos/:id | photos#update | update a specific photo |
| DELETE | /photos/:id | photos#destroy | delete a specific photo |
2009-02-05 20:57:02 -05:00
2012-12-02 15:14:08 -05:00
NOTE: Because the router uses the HTTP verb and URL to match inbound requests, four URLs map to seven different actions.
2012-09-06 22:26:59 -04:00
NOTE: Rails routes are matched in the order they are specified, so if you have a `resources :photos` above a `get 'photos/poll'` the `show` action's route for the `resources` line will be matched before the `get` line. To fix this, move the `get` line **above** the `resources` line so that it is matched first.
2010-12-28 19:54:42 -05:00
2012-12-02 15:16:07 -05:00
### Path and URL Helpers
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
Creating a resourceful route will also expose a number of helpers to the controllers in your application. In the case of `resources :photos` :
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
* `photos_path` returns `/photos`
* `new_photo_path` returns `/photos/new`
* `edit_photo_path(:id)` returns `/photos/:id/edit` (for instance, `edit_photo_path(10)` returns `/photos/10/edit` )
* `photo_path(:id)` returns `/photos/:id` (for instance, `photo_path(10)` returns `/photos/10` )
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
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.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Defining Multiple Resources at the Same Time
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
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` :
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2010-01-31 23:50:44 -05:00
resources :photos, :books, :videos
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-12-02 15:52:12 -05:00
This works exactly the same as:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2010-01-31 23:50:44 -05:00
resources :photos
resources :books
resources :videos
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Singular Resources
2009-02-05 20:57:02 -05:00
2012-12-02 15:52:12 -05:00
Sometimes, you have a resource that clients always look up without referencing an ID. For example, you would like `/profile` to always show 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:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
get 'profile', to: 'users#show'
2012-09-01 17:08:06 -04:00
```
2010-05-13 10:12:25 -04:00
2013-04-10 20:40:18 -04:00
Passing a `String` to `match` will expect a `controller#action` format, while passing a `Symbol` will map directly to an action:
```ruby
get 'profile', to: :show
```
2012-12-02 15:52:12 -05:00
This resourceful route:
2010-05-13 10:12:25 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2010-01-31 23:50:44 -05:00
resource :geocoder
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
creates six different routes in your application, all mapping to the `Geocoders` controller:
2009-02-05 20:57:02 -05:00
2013-10-31 06:45:09 -04:00
| HTTP Verb | Path | Controller#Action | Used for |
| --------- | -------------- | ----------------- | --------------------------------------------- |
| GET | /geocoder/new | geocoders#new | return an HTML form for creating the geocoder |
| POST | /geocoder | geocoders#create | create the new geocoder |
| GET | /geocoder | geocoders#show | display the one and only geocoder resource |
| GET | /geocoder/edit | geocoders#edit | return an HTML form for editing the geocoder |
| PATCH/PUT | /geocoder | geocoders#update | update the one and only geocoder resource |
| DELETE | /geocoder | geocoders#destroy | delete the geocoder resource |
2009-02-05 20:57:02 -05:00
2013-02-18 04:45:58 -05:00
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. So that, for example, `resource :photo` and `resources :photos` creates both singular and plural routes that map to the same controller (`PhotosController`).
2009-02-05 20:57:02 -05:00
2010-04-10 04:51:41 -04:00
A singular resourceful route generates these helpers:
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
* `new_geocoder_path` returns `/geocoder/new`
* `edit_geocoder_path` returns `/geocoder/edit`
* `geocoder_path` returns `/geocoder`
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
As with plural resources, the same helpers ending in `_url` will also include the host, port and path prefix.
2009-02-05 20:57:02 -05:00
2013-06-07 18:32:50 -04:00
WARNING: A [long-standing bug ](https://github.com/rails/rails/issues/1769 ) prevents `form_for` from working automatically with singular resources. As a workaround, specify the URL for the form directly, like so:
2013-06-20 00:31:08 -04:00
```ruby
2013-06-07 18:32:50 -04:00
form_for @geocoder , url: geocoder_path do |f|
```
2012-09-01 17:25:58 -04:00
### Controller Namespaces and Routing
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
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:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2010-10-19 08:40:47 -04:00
namespace :admin do
2010-04-10 04:51:41 -04:00
resources :posts, :comments
2009-02-05 20:57:02 -05:00
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
This will create a number of routes for each of the `posts` and `comments` controller. For `Admin::PostsController` , Rails will create:
2009-02-05 20:57:02 -05:00
2013-10-31 06:45:09 -04:00
| HTTP Verb | Path | Controller#Action | Named Helper |
| --------- | --------------------- | ------------------- | ------------------------- |
| GET | /admin/posts | admin/posts#index | admin_posts_path |
| GET | /admin/posts/new | admin/posts#new | new_admin_post_path |
| POST | /admin/posts | admin/posts#create | admin_posts_path |
| GET | /admin/posts/:id | admin/posts#show | admin_post_path(:id) |
| GET | /admin/posts/:id/edit | admin/posts#edit | edit_admin_post_path(:id) |
| PATCH/PUT | /admin/posts/:id | admin/posts#update | admin_post_path(:id) |
| DELETE | /admin/posts/:id | admin/posts#destroy | admin_post_path(:id) |
2009-02-05 20:57:02 -05:00
2012-12-02 15:52:12 -05:00
If you want to route `/posts` (without the prefix `/admin` ) to `Admin::PostsController` , you could use:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
scope module: 'admin' do
2010-04-10 04:51:41 -04:00
resources :posts, :comments
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-12-02 15:52:12 -05:00
or, for a single case:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
resources :posts, module: 'admin'
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-12-02 15:52:12 -05:00
If you want to route `/admin/posts` to `PostsController` (without the `Admin::` module prefix), you could use:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
scope '/admin' do
2010-04-10 04:51:41 -04:00
resources :posts, :comments
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-12-02 15:52:12 -05:00
or, for a single case:
2010-04-05 11:07:49 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
resources :posts, path: '/admin/posts'
2012-09-01 17:08:06 -04:00
```
2010-04-05 11:07:49 -04:00
2012-09-01 21:37:59 -04:00
In each of these cases, the named routes remain the same as if you did not use `scope` . In the last case, the following paths map to `PostsController` :
2010-04-05 11:07:49 -04:00
2013-10-31 06:45:09 -04:00
| HTTP Verb | Path | Controller#Action | Named Helper |
| --------- | --------------------- | ----------------- | ------------------- |
| GET | /admin/posts | posts#index | posts_path |
| GET | /admin/posts/new | posts#new | new_post_path |
| POST | /admin/posts | posts#create | posts_path |
| GET | /admin/posts/:id | posts#show | post_path(:id) |
| GET | /admin/posts/:id/edit | posts#edit | edit_post_path(:id) |
| PATCH/PUT | /admin/posts/:id | posts#update | post_path(:id) |
| DELETE | /admin/posts/:id | posts#destroy | post_path(:id) |
2010-04-05 11:07:49 -04:00
2012-09-01 17:25:58 -04:00
### Nested Resources
2009-02-05 20:57:02 -05:00
It's common to have resources that are logically children of other resources. For example, suppose your application includes these models:
2012-09-01 17:08:06 -04:00
```ruby
2009-02-05 20:57:02 -05:00
class Magazine < ActiveRecord::Base
has_many :ads
end
class Ad < ActiveRecord::Base
belongs_to :magazine
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2010-04-10 04:51:41 -04:00
Nested routes allow you to capture this relationship in your routing. In this case, you could include this route declaration:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2010-01-31 23:50:44 -05:00
resources :magazines do
resources :ads
2009-02-05 20:57:02 -05:00
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
In addition to the routes for magazines, this declaration will also route ads to an `AdsController` . The ad URLs require a magazine:
2009-02-05 20:57:02 -05:00
2013-10-31 06:45:09 -04:00
| HTTP Verb | Path | Controller#Action | Used for |
| --------- | ------------------------------------ | ----------------- | -------------------------------------------------------------------------- |
| GET | /magazines/:magazine_id/ads | ads#index | display a list of all ads for a specific magazine |
| GET | /magazines/:magazine_id/ads/new | ads#new | return an HTML form for creating a new ad belonging to a specific magazine |
| POST | /magazines/:magazine_id/ads | ads#create | create a new ad belonging to a specific magazine |
| GET | /magazines/:magazine_id/ads/:id | ads#show | display a specific ad belonging to a specific magazine |
| GET | /magazines/:magazine_id/ads/:id/edit | ads#edit | return an HTML form for editing an ad belonging to a specific magazine |
| PATCH/PUT | /magazines/:magazine_id/ads/:id | ads#update | update a specific ad belonging to a specific magazine |
| DELETE | /magazines/:magazine_id/ads/:id | ads#destroy | delete a specific ad belonging to a specific magazine |
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
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)`).
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
#### Limits to Nesting
2009-02-05 20:57:02 -05:00
You can nest resources within other nested resources if you like. For example:
2012-09-01 17:08:06 -04:00
```ruby
2010-01-31 23:50:44 -05:00
resources :publishers do
resources :magazines do
resources :photos
2009-02-05 20:57:02 -05:00
end
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-12-02 15:52:12 -05:00
Deeply-nested resources quickly become cumbersome. In this case, for example, the application would recognize paths such as:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
/publishers/1/magazines/2/photos/3
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-02 01:08:20 -04:00
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 ](http://weblog.jamisbuck.org/2007/2/5/nesting-resources ) by Jamis Buck proposes a rule of thumb for good Rails design:
2009-02-05 20:57:02 -05:00
2009-02-11 13:30:15 -05:00
TIP: _Resources should never be nested more than 1 level deep._
2009-02-05 20:57:02 -05:00
2012-12-02 12:46:22 -05:00
#### Shallow Nesting
One way to avoid deep nesting (as recommended above) is to generate the collection actions scoped under the parent, so as to get a sense of the hierarchy, but to not nest the member actions. In other words, to only build routes with the minimal amount of information to uniquely identify the resource, like this:
```ruby
resources :posts do
resources :comments, only: [:index, :new, :create]
end
resources :comments, only: [:show, :edit, :update, :destroy]
```
This idea strikes a balance between descriptive routes and deep nesting. There exists shorthand syntax to achieve just that, via the `:shallow` option:
```ruby
resources :posts do
resources :comments, shallow: true
end
```
This will generate the exact same routes as the first example. You can also specify the `:shallow` option in the parent resource, in which case all of the nested resources will be shallow:
```ruby
resources :posts, shallow: true do
resources :comments
resources :quotes
resources :drafts
end
```
The `shallow` method of the DSL creates a scope inside of which every nesting is shallow. This generates the same routes as the previous example:
```ruby
shallow do
resources :posts do
resources :comments
resources :quotes
resources :drafts
end
end
```
2013-11-18 23:10:21 -05:00
There exist two options for `scope` to customize shallow routes. `:shallow_path` prefixes member paths with the specified parameter:
2012-12-02 12:46:22 -05:00
```ruby
scope shallow_path: "sekret" do
resources :posts do
resources :comments, shallow: true
end
end
```
The comments resource here will have the following routes generated for it:
2013-10-31 06:45:09 -04:00
| HTTP Verb | Path | Controller#Action | Named Helper |
| --------- | -------------------------------------- | ----------------- | ------------------- |
| GET | /posts/:post_id/comments(.:format) | comments#index | post_comments |
| POST | /posts/:post_id/comments(.:format) | comments#create | post_comments |
| GET | /posts/:post_id/comments/new(.:format) | comments#new | new_post_comment |
| GET | /sekret/comments/:id/edit(.:format) | comments#edit | edit_comment |
| GET | /sekret/comments/:id(.:format) | comments#show | comment |
| PATCH/PUT | /sekret/comments/:id(.:format) | comments#update | comment |
| DELETE | /sekret/comments/:id(.:format) | comments#destroy | comment |
2012-12-02 12:46:22 -05:00
The `:shallow_prefix` option adds the specified parameter to the named helpers:
```ruby
scope shallow_prefix: "sekret" do
resources :posts do
resources :comments, shallow: true
end
end
```
The comments resource here will have the following routes generated for it:
2013-10-31 06:45:09 -04:00
| HTTP Verb | Path | Controller#Action | Named Helper |
| --------- | -------------------------------------- | ----------------- | ------------------- |
| GET | /posts/:post_id/comments(.:format) | comments#index | post_comments |
| POST | /posts/:post_id/comments(.:format) | comments#create | post_comments |
| GET | /posts/:post_id/comments/new(.:format) | comments#new | new_post_comment |
| GET | /comments/:id/edit(.:format) | comments#edit | edit_sekret_comment |
| GET | /comments/:id(.:format) | comments#show | sekret_comment |
| PATCH/PUT | /comments/:id(.:format) | comments#update | sekret_comment |
| DELETE | /comments/:id(.:format) | comments#destroy | sekret_comment |
2012-12-02 12:46:22 -05:00
2012-09-01 17:25:58 -04:00
### Routing concerns
2012-08-09 23:06:16 -04:00
2013-11-18 23:10:21 -05:00
Routing Concerns allows you to declare common routes that can be reused inside other resources and routes. To define a concern:
2012-08-09 23:06:16 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-08-09 23:06:16 -04:00
concern :commentable do
resources :comments
end
concern :image_attachable do
resources :images, only: :index
end
2012-09-01 17:08:06 -04:00
```
2012-08-09 23:06:16 -04:00
2012-12-02 15:52:12 -05:00
These concerns can be used in resources to avoid code duplication and share behavior across routes:
2012-08-09 23:06:16 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-08-09 23:06:16 -04:00
resources :messages, concerns: :commentable
resources :posts, concerns: [:commentable, :image_attachable]
2012-09-01 17:08:06 -04:00
```
2012-08-09 23:06:16 -04:00
2012-12-02 15:43:23 -05:00
The above is equivalent to:
```ruby
resources :messages do
resources :comments
end
resources :posts do
resources :comments
resources :images, only: :index
end
```
2012-08-09 23:06:16 -04:00
Also you can use them in any place that you want inside the routes, for example in a scope or namespace call:
2012-09-01 17:08:06 -04:00
```ruby
2012-08-09 23:06:16 -04:00
namespace :posts do
concerns :commentable
end
2012-09-01 17:08:06 -04:00
```
2012-08-09 23:06:16 -04:00
2012-09-01 17:25:58 -04:00
### Creating Paths and URLs From Objects
2009-02-05 20:57:02 -05:00
2010-07-21 18:32:39 -04:00
In addition to using the routing helpers, Rails can also create paths and URLs from an array of parameters. For example, suppose you have this set of routes:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2010-01-31 23:50:44 -05:00
resources :magazines do
resources :ads
2009-02-05 20:57:02 -05:00
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-12-02 15:52:12 -05:00
When using `magazine_ad_path` , you can pass in instances of `Magazine` and `Ad` instead of the numeric IDs:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```erb
2012-11-08 00:36:50 -05:00
< %= link_to 'Ad details', magazine_ad_path(@magazine, @ad ) %>
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
You can also use `url_for` with a set of objects, and Rails will automatically determine which route you want:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```erb
2012-11-08 00:36:50 -05:00
< %= link_to 'Ad details', url_for([@magazine, @ad ]) %>
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
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:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```erb
2012-11-08 00:36:50 -05:00
< %= link_to 'Ad details', [@magazine, @ad ] %>
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-02-28 08:49:47 -05:00
If you wanted to link to just a magazine:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```erb
2012-11-08 00:36:50 -05:00
< %= link_to 'Magazine details', @magazine %>
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-02-28 08:49:47 -05:00
For other actions, you just need to insert the action name as the first element of the array:
2012-02-26 19:07:16 -05:00
2012-09-01 17:08:06 -04:00
```erb
2012-11-08 00:36:50 -05:00
< %= link_to 'Edit Ad', [:edit, @magazine , @ad ] %>
2012-09-01 17:08:06 -04:00
```
2012-02-26 19:07:16 -05:00
2010-04-10 04:51:41 -04:00
This allows you to treat instances of your models as URLs, and is a key advantage to using the resourceful style.
2009-02-05 20:57:02 -05:00
2013-05-30 12:43:40 -04:00
### Adding More RESTful Actions
2009-02-05 20:57:02 -05:00
2010-04-10 04:51:41 -04:00
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.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
#### Adding Member Routes
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
To add a member route, just add a `member` block into the resource block:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2010-01-31 23:50:44 -05:00
resources :photos do
member do
2010-08-16 20:37:28 -04:00
get 'preview'
2010-01-31 23:50:44 -05:00
end
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-12-10 18:47:21 -05:00
This will recognize `/photos/1/preview` with GET, and route to the `preview` action of `PhotosController` , with the resource id value passed in `params[:id]` . It will also create the `preview_photo_url` and `preview_photo_path` helpers.
2009-02-05 20:57:02 -05:00
2013-10-31 06:45:09 -04:00
Within the block of member routes, each route name specifies the HTTP verb
will be recognized. You can use `get` , `patch` , `put` , `post` , or `delete` here
. If you don't have multiple `member` routes, you can also pass `:on` to a
route, eliminating the block:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2010-01-31 23:50:44 -05:00
resources :photos do
2012-10-10 10:35:50 -04:00
get 'preview', on: :member
2010-01-31 23:50:44 -05:00
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-12-10 18:47:21 -05:00
You can leave out the `:on` option, this will create the same member route except that the resource id value will be available in `params[:photo_id]` instead of `params[:id]` .
2012-09-01 17:25:58 -04:00
#### Adding Collection Routes
2009-02-05 20:57:02 -05:00
2010-04-10 04:51:41 -04:00
To add a route to the collection:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2010-01-31 23:50:44 -05:00
resources :photos do
collection do
2010-08-16 20:37:28 -04:00
get 'search'
2010-01-31 23:50:44 -05:00
end
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
This will enable Rails to recognize paths 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.
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
Just as with member routes, you can pass `:on` to a route:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2010-01-31 23:50:44 -05:00
resources :photos do
2012-10-10 10:35:50 -04:00
get 'search', on: :collection
2010-01-31 23:50:44 -05:00
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-25 12:29:53 -04:00
#### Adding Routes for Additional New Actions
To add an alternate new action using the `:on` shortcut:
```ruby
resources :comments do
2012-10-10 10:35:50 -04:00
get 'preview', on: :new
2012-09-25 12:29:53 -04:00
end
```
This will enable Rails to recognize paths such as `/comments/new/preview` with GET, and route to the `preview` action of `CommentsController` . It will also create the `preview_new_comment_url` and `preview_new_comment_path` route helpers.
2012-12-02 16:10:35 -05:00
TIP: 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.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
Non-Resourceful Routes
----------------------
2009-02-05 20:57:02 -05:00
2010-04-10 04:51:41 -04:00
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.
2009-02-05 20:57:02 -05:00
2010-04-10 04:51:41 -04:00
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.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Bound Parameters
2009-02-05 20:57:02 -05:00
2013-03-18 07:38:10 -04:00
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 this route:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-04-24 23:32:09 -04:00
get ':controller(/:action(/:id))'
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
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#index` , since `:action` and `:id` are optional parameters, denoted by parentheses.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Dynamic Segments
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
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:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-04-24 23:32:09 -04:00
get ':controller/:action/:id/:user_id'
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
An incoming path 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"` .
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
NOTE: You can't use `:namespace` or `:module` with a `:controller` path segment. If you need to do this then use a constraint on :controller that matches the namespace you require. e.g:
2010-07-07 00:31:54 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-10-10 10:35:50 -04:00
get ':controller(/:action(/:id))', controller: /admin\/[^\/]+/
2012-09-01 17:08:06 -04:00
```
2010-07-07 00:31:54 -04:00
2012-12-02 16:20:48 -05:00
TIP: By default, dynamic segments don't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within a dynamic segment, add a constraint that overrides this – for example, `id: /[^\/]+/` allows anything except a slash.
2011-02-13 19:40:53 -05:00
2012-09-01 17:25:58 -04:00
### Static Segments
2009-02-05 20:57:02 -05:00
2012-12-02 16:21:29 -05:00
You can specify static segments when creating a route by not prepending a colon to a fragment:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-04-24 23:32:09 -04:00
get ':controller/:action/:id/with_user/:user_id'
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-11-08 00:36:50 -05:00
This route would respond to paths such as `/photos/show/1/with_user/2` . In this case, `params` would be `{ controller: 'photos', action: 'show', id: '1', user_id: '2' }` .
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### The Query String
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
The `params` will also include any parameters from the query string. For example, with this route:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-04-24 23:32:09 -04:00
get ':controller/:action/:id'
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-11-08 00:36:50 -05:00
An incoming path 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' }` .
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Defining Defaults
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
You do not need to explicitly use the `:controller` and `:action` symbols within a route. You can supply them as defaults:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
get 'photos/:id', to: 'photos#show'
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
With this route, Rails will match an incoming path of `/photos/12` to the `show` action of `PhotosController` .
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
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:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
get 'photos/:id', to: 'photos#show', defaults: { format: 'jpg' }
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
Rails would match `photos/12` to the `show` action of `PhotosController` , and set `params[:format]` to `"jpg"` .
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Naming Routes
2009-02-05 20:57:02 -05:00
2012-12-02 15:52:12 -05:00
You can specify a name for any route using the `:as` option:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
get 'exit', to: 'sessions#destroy', as: :logout
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
This will create `logout_path` and `logout_url` as named helpers in your application. Calling `logout_path` will return `/exit`
2009-02-05 20:57:02 -05:00
2012-05-26 02:12:06 -04:00
You can also use this to override routing methods defined by resources, like this:
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
get ':username', to: 'users#show', as: :user
2012-09-01 17:08:06 -04:00
```
2012-05-26 02:12:06 -04:00
2012-09-01 21:37:59 -04:00
This will define a `user_path` method that will be available in controllers, helpers and views that will go to a route such as `/bob` . Inside the `show` action of `UsersController` , `params[:username]` will contain the username for the user. Change `:username` in the route definition if you do not want your parameter name to be `:username` .
2012-05-26 02:12:06 -04:00
2012-09-01 17:25:58 -04:00
### HTTP Verb Constraints
2010-11-15 11:26:57 -05:00
2012-09-01 21:37:59 -04:00
In general, you should use the `get` , `post` , `put` and `delete` methods to constrain a route to a particular verb. You can use the `match` method with the `:via` option to match multiple verbs at once:
2010-11-15 11:26:57 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
match 'photos', to: 'photos#show', via: [:get, :post]
2012-09-01 17:08:06 -04:00
```
2010-11-15 11:26:57 -05:00
2012-10-10 10:35:50 -04:00
You can match all verbs to a particular route using `via: :all` :
2010-11-15 11:26:57 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
match 'photos', to: 'photos#show', via: :all
2012-09-01 17:08:06 -04:00
```
2010-11-15 11:26:57 -05:00
2012-12-02 16:27:13 -05:00
NOTE: Routing both `GET` and `POST` requests to a single action has security implications. In general, you should avoid routing all verbs to an action unless you have a good reason to.
2010-11-15 11:26:57 -05:00
2012-09-01 17:25:58 -04:00
### Segment Constraints
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
You can use the `:constraints` option to enforce a format for a dynamic segment:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
get 'photos/:id', to: 'photos#show', constraints: { id: /[A-Z]\d{5}/ }
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-12-02 16:31:12 -05:00
This route would match paths such as `/photos/A12345` , but not `/photos/893` . You can more succinctly express the same route this way:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
get 'photos/:id', to: 'photos#show', id: /[A-Z]\d{5}/
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
`:constraints` takes regular expressions with the restriction that regexp anchors can't be used. For example, the following route will not work:
2010-06-25 10:07:09 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
get '/:id', to: 'posts#show', constraints: {id: /^\d/}
2012-09-01 17:08:06 -04:00
```
2010-06-25 19:50:56 -04:00
However, note that you don't need to use anchors because all routes are anchored at the start.
2012-09-01 21:37:59 -04:00
For example, the following routes would allow for `posts` with `to_param` values like `1-hello-world` that always begin with a number and `users` with `to_param` values like `david` that never begin with a number to share the root namespace:
2010-06-25 19:50:56 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
get '/:id', to: 'posts#show', constraints: { id: /\d.+/ }
get '/:username', to: 'users#show'
2012-09-01 17:08:06 -04:00
```
2010-06-25 10:07:09 -04:00
2012-09-01 17:25:58 -04:00
### Request-Based Constraints
2010-04-10 04:51:41 -04:00
2012-09-01 21:37:59 -04:00
You can also constrain a route based on any method on the < a href = "action_controller_overview.html#the-request-object" > Request</ a > object that returns a `String` .
2010-04-10 04:51:41 -04:00
You specify a request-based constraint the same way that you specify a segment constraint:
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
get 'photos', constraints: {subdomain: 'admin'}
2012-09-01 17:08:06 -04:00
```
2010-04-10 04:51:41 -04:00
2011-01-01 16:23:15 -05:00
You can also specify constraints in a block form:
2010-04-10 04:51:41 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2010-10-19 08:40:47 -04:00
namespace :admin do
2012-11-08 00:36:50 -05:00
constraints subdomain: 'admin' do
2010-04-10 04:51:41 -04:00
resources :photos
end
end
2012-09-01 17:08:06 -04:00
```
2010-04-10 04:51:41 -04:00
2012-09-01 17:25:58 -04:00
### Advanced Constraints
2010-04-10 04:51:41 -04:00
2012-09-01 21:37:59 -04:00
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:
2010-04-10 04:51:41 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2010-04-10 04:51:41 -04:00
class BlacklistConstraint
def initialize
@ips = Blacklist.retrieve_ips
end
def matches?(request)
@ips .include?(request.remote_ip)
end
end
TwitterClone::Application.routes.draw do
2012-11-08 00:36:50 -05:00
get '*path', to: 'blacklist#index',
2012-10-10 10:35:50 -04:00
constraints: BlacklistConstraint.new
2010-04-10 04:51:41 -04:00
end
2012-09-01 17:08:06 -04:00
```
2010-04-10 04:51:41 -04:00
2012-03-28 15:05:46 -04:00
You can also specify constraints as a lambda:
2012-09-01 17:08:06 -04:00
```ruby
2012-03-28 15:05:46 -04:00
TwitterClone::Application.routes.draw do
2012-11-08 00:36:50 -05:00
get '*path', to: 'blacklist#index',
2012-10-10 10:35:50 -04:00
constraints: lambda { |request| Blacklist.retrieve_ips.include?(request.remote_ip) }
2012-03-28 15:05:46 -04:00
end
2012-09-01 17:08:06 -04:00
```
2012-03-28 15:05:46 -04:00
2012-09-01 21:37:59 -04:00
Both the `matches?` method and the lambda gets the `request` object as an argument.
2012-03-28 15:05:46 -04:00
2012-12-02 16:43:47 -05:00
### Route Globbing and Wildcard Segments
2009-02-05 20:57:02 -05:00
2012-12-02 15:52:12 -05:00
Route globbing is a way to specify that a particular parameter should be matched to all the remaining parts of a route. For example:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
get 'photos/*other', to: 'photos#unknown'
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-12-02 16:43:47 -05:00
This route would match `photos/12` or `/photos/long/path/to/12` , setting `params[:other]` to `"12"` or `"long/path/to/12"` . The fragments prefixed with a star are called "wildcard segments".
2010-04-10 04:51:41 -04:00
2012-12-02 15:52:12 -05:00
Wildcard segments can occur anywhere in a route. For example:
2010-08-15 19:10:34 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
get 'books/*section/:title', to: 'books#show'
2012-09-01 17:08:06 -04:00
```
2010-08-15 19:10:34 -04:00
2012-11-08 00:36:50 -05:00
would match `books/some/section/last-words-a-memoir` with `params[:section]` equals `'some/section'` , and `params[:title]` equals `'last-words-a-memoir'` .
2010-08-15 19:10:34 -04:00
2012-12-02 16:20:48 -05:00
Technically, a route can have even more than one wildcard segment. The matcher assigns segments to parameters in an intuitive way. For example:
2010-08-15 19:10:34 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
get '*a/foo/*b', to: 'test#index'
2012-09-01 17:08:06 -04:00
```
2010-08-15 19:10:34 -04:00
2012-11-08 00:36:50 -05:00
would match `zoo/woo/foo/bar/baz` with `params[:a]` equals `'zoo/woo'` , and `params[:b]` equals `'bar/baz'` .
2010-08-15 19:10:34 -04:00
2012-11-08 00:36:50 -05:00
NOTE: By requesting `'/foo/bar.json'` , your `params[:pages]` will be equals to `'foo/bar'` with the request format of JSON. If you want the old 3.0.x behavior back, you could supply `format: false` like this:
2011-03-28 15:59:24 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
get '*pages', to: 'pages#show', format: false
2012-09-01 17:08:06 -04:00
```
2011-03-28 15:59:24 -04:00
2012-10-10 10:35:50 -04:00
NOTE: If you want to make the format segment mandatory, so it cannot be omitted, you can supply `format: true` like this:
2011-07-25 17:13:26 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
get '*pages', to: 'pages#show', format: true
2012-09-01 17:08:06 -04:00
```
2011-07-25 17:13:26 -04:00
2012-09-01 17:25:58 -04:00
### Redirection
2010-04-10 04:51:41 -04:00
2012-09-01 21:37:59 -04:00
You can redirect any path to another path using the `redirect` helper in your router:
2010-04-10 04:51:41 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
get '/stories', to: redirect('/posts')
2012-09-01 17:08:06 -04:00
```
2010-04-10 04:51:41 -04:00
You can also reuse dynamic segments from the match in the path to redirect to:
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
get '/stories/:name', to: redirect('/posts/%{name}')
2012-09-01 17:08:06 -04:00
```
2010-04-10 04:51:41 -04:00
2013-06-25 01:58:33 -04:00
You can also provide a block to redirect, which receives the symbolized path parameters and the request object:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2013-06-25 01:58:33 -04:00
get '/stories/:name', to: redirect {|path_params, req| "/posts/#{path_params[:name].pluralize}" }
get '/stories', to: redirect {|path_params, req| "/posts/#{req.subdomain}" }
2012-09-01 17:08:06 -04:00
```
2010-04-10 04:51:41 -04:00
2011-10-06 02:03:46 -04:00
Please note that this redirection is a 301 "Moved Permanently" redirect. Keep in mind that some web browsers or proxy servers will cache this type of redirect, making the old page inaccessible.
2011-10-05 14:31:14 -04:00
2012-09-01 21:37:59 -04:00
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.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Routing to Rack Applications
2009-02-05 20:57:02 -05:00
2012-12-02 16:20:48 -05:00
Instead of a String like `'posts#index'` , which corresponds to the `index` action in the `PostsController` , you can specify any < a href = "rails_on_rack.html" > Rack application</ a > as the endpoint for a matcher:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
match '/application.js', to: Sprockets, via: :all
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-10-10 10:35:50 -04:00
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. This is an appropriate use of `via: :all` , as you will want to allow your Rack application to handle all verbs as it considers appropriate.
2010-04-10 04:51:41 -04:00
2012-11-08 00:36:50 -05:00
NOTE: For the curious, `'posts#index'` actually expands out to `PostsController.action(:index)` , which returns a valid Rack application.
2010-04-10 04:51:41 -04:00
2012-09-01 21:37:59 -04:00
### Using `root`
2010-04-10 04:51:41 -04:00
2012-11-08 00:36:50 -05:00
You can specify what Rails should route `'/'` to with the `root` method:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-10-10 10:35:50 -04:00
root to: 'pages#main'
2012-03-05 12:11:13 -05:00
root 'pages#main' # shortcut for the above
2012-09-01 17:08:06 -04:00
```
2010-04-10 04:51:41 -04:00
2012-12-11 04:29:19 -05:00
You should put the `root` route at the top of the file, because it is the most popular route and should be matched first.
2010-04-10 04:51:41 -04:00
2012-09-01 21:37:59 -04:00
NOTE: The `root` route only routes `GET` requests to the action.
2012-04-24 23:32:09 -04:00
2013-05-28 08:34:47 -04:00
You can also use root inside namespaces and scopes as well. For example:
2013-02-26 12:43:32 -05:00
```ruby
namespace :admin do
root to: "admin#index"
end
root to: "home#index"
```
2012-09-01 17:25:58 -04:00
### Unicode character routes
2012-06-05 11:59:01 -04:00
2012-12-02 15:52:12 -05:00
You can specify unicode character routes directly. For example:
2012-06-05 11:59:01 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
get 'こんにちは', to: 'welcome#index'
2012-09-01 17:08:06 -04:00
```
2012-06-05 11:59:01 -04:00
2012-09-01 17:25:58 -04:00
Customizing Resourceful Routes
------------------------------
2010-04-10 04:51:41 -04:00
2012-09-01 21:37:59 -04:00
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.
2010-04-10 04:51:41 -04:00
2012-09-01 17:25:58 -04:00
### Specifying a Controller to Use
2010-04-10 04:51:41 -04:00
2012-09-01 21:37:59 -04:00
The `:controller` option lets you explicitly specify a controller to use for the resource. For example:
2010-04-10 04:51:41 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
resources :photos, controller: 'images'
2012-09-01 17:08:06 -04:00
```
2010-04-10 04:51:41 -04:00
2012-09-01 21:37:59 -04:00
will recognize incoming paths beginning with `/photos` but route to the `Images` controller:
2010-04-10 04:51:41 -04:00
2013-10-31 06:45:09 -04:00
| HTTP Verb | Path | Controller#Action | Named Helper |
| --------- | ---------------- | ----------------- | -------------------- |
| GET | /photos | images#index | photos_path |
| GET | /photos/new | images#new | new_photo_path |
| POST | /photos | images#create | photos_path |
| GET | /photos/:id | images#show | photo_path(:id) |
| GET | /photos/:id/edit | images#edit | edit_photo_path(:id) |
| PATCH/PUT | /photos/:id | images#update | photo_path(:id) |
| DELETE | /photos/:id | images#destroy | photo_path(:id) |
2010-04-10 04:51:41 -04:00
2012-09-01 21:37:59 -04:00
NOTE: Use `photos_path` , `new_photo_path` , etc. to generate paths for this resource.
2010-04-10 04:51:41 -04:00
2013-01-23 03:31:16 -05:00
For namespaced controllers you can use the directory notation. For example:
```ruby
resources :user_permissions, controller: 'admin/user_permissions'
```
This will route to the `Admin::UserPermissions` controller.
2013-03-16 04:08:01 -04:00
NOTE: Only the directory notation is supported. Specifying the
2013-09-06 14:41:04 -04:00
controller with Ruby constant notation (eg. `controller: 'Admin::UserPermissions'` )
can lead to routing problems and results in
2013-01-23 03:31:16 -05:00
a warning.
2012-09-01 17:25:58 -04:00
### Specifying Constraints
2010-04-10 04:51:41 -04:00
2012-09-01 21:37:59 -04:00
You can use the `:constraints` option to specify a required format on the implicit `id` . For example:
2010-04-10 04:51:41 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-10-10 10:35:50 -04:00
resources :photos, constraints: {id: /[A-Z][A-Z][0-9]+/}
2012-09-01 17:08:06 -04:00
```
2010-04-10 04:51:41 -04:00
2012-09-01 21:37:59 -04:00
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.
2010-04-10 04:51:41 -04:00
2010-06-14 18:46:30 -04:00
You can specify a single constraint to apply to a number of routes by using the block form:
2010-04-10 04:51:41 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-10-10 10:35:50 -04:00
constraints(id: /[A-Z][A-Z][0-9]+/) do
2010-04-10 04:51:41 -04:00
resources :photos
resources :accounts
end
2012-09-01 17:08:06 -04:00
```
2010-04-10 04:51:41 -04:00
2010-12-10 13:04:48 -05:00
NOTE: Of course, you can use the more advanced constraints available in non-resourceful routes in this context.
2010-04-10 04:51:41 -04:00
2012-10-10 10:35:50 -04:00
TIP: By default the `:id` parameter doesn't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within an `:id` add a constraint which overrides this - for example `id: /[^\/]+/` allows anything except a slash.
2011-02-13 19:40:53 -05:00
2012-09-01 17:25:58 -04:00
### Overriding the Named Helpers
2010-04-10 04:51:41 -04:00
2012-09-01 21:37:59 -04:00
The `:as` option lets you override the normal naming for the named route helpers. For example:
2010-04-10 04:51:41 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
resources :photos, as: 'images'
2012-09-01 17:08:06 -04:00
```
2010-04-10 04:51:41 -04:00
2012-09-01 21:37:59 -04:00
will recognize incoming paths beginning with `/photos` and route the requests to `PhotosController` , but use the value of the :as option to name the helpers.
2010-04-10 04:51:41 -04:00
2013-10-31 06:45:09 -04:00
| HTTP Verb | Path | Controller#Action | Named Helper |
| --------- | ---------------- | ----------------- | -------------------- |
| GET | /photos | photos#index | images_path |
| GET | /photos/new | photos#new | new_image_path |
| POST | /photos | photos#create | images_path |
| GET | /photos/:id | photos#show | image_path(:id) |
| GET | /photos/:id/edit | photos#edit | edit_image_path(:id) |
| PATCH/PUT | /photos/:id | photos#update | image_path(:id) |
| DELETE | /photos/:id | photos#destroy | image_path(:id) |
2010-04-10 04:51:41 -04:00
2012-09-01 21:37:59 -04:00
### Overriding the `new` and `edit` Segments
2010-04-10 04:51:41 -04:00
2012-09-01 21:37:59 -04:00
The `:path_names` option lets you override the automatically-generated "new" and "edit" segments in paths:
2010-04-10 04:51:41 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-10-10 10:35:50 -04:00
resources :photos, path_names: { new: 'make', edit: 'change' }
2012-09-01 17:08:06 -04:00
```
2010-04-10 04:51:41 -04:00
2012-12-02 15:52:12 -05:00
This would cause the routing to recognize paths such as:
2010-04-10 04:51:41 -04:00
2012-09-01 17:08:06 -04:00
```
2010-04-10 04:51:41 -04:00
/photos/make
/photos/1/change
2012-09-01 17:08:06 -04:00
```
2010-04-10 04:51:41 -04:00
2012-09-01 21:37:59 -04:00
NOTE: The actual action names aren't changed by this option. The two paths shown would still route to the `new` and `edit` actions.
2010-04-10 04:51:41 -04:00
2010-12-10 13:04:48 -05:00
TIP: If you find yourself wanting to change this option uniformly for all of your routes, you can use a scope.
2010-04-10 04:51:41 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
scope path_names: { new: 'make' } do
2010-04-10 04:51:41 -04:00
# rest of your routes
2009-02-05 20:57:02 -05:00
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Prefixing the Named Route Helpers
2009-02-05 20:57:02 -05:00
2012-12-02 15:52:12 -05:00
You can use the `:as` option to prefix the named route helpers that Rails generates for a route. Use this option to prevent name collisions between routes using a path scope. For example:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
scope 'admin' do
resources :photos, as: 'admin_photos'
2010-04-10 04:51:41 -04:00
end
2009-02-05 20:57:02 -05:00
2010-04-10 04:51:41 -04:00
resources :photos
2012-09-01 17:08:06 -04:00
```
2010-04-10 04:51:41 -04:00
2012-09-01 21:37:59 -04:00
This will provide route helpers such as `admin_photos_path` , `new_admin_photo_path` etc.
2010-04-10 04:51:41 -04:00
2012-09-01 21:37:59 -04:00
To prefix a group of route helpers, use `:as` with `scope` :
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
scope 'admin', as: 'admin' do
2010-04-10 04:51:41 -04:00
resources :photos, :accounts
end
resources :photos, :accounts
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
This will generate routes such as `admin_photos_path` and `admin_accounts_path` which map to `/admin/photos` and `/admin/accounts` respectively.
2010-12-31 02:45:03 -05:00
2012-09-01 21:37:59 -04:00
NOTE: The `namespace` scope will automatically add `:as` as well as `:module` and `:path` prefixes.
2010-04-10 04:51:41 -04:00
2010-12-31 02:45:03 -05:00
You can prefix routes with a named parameter also:
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
scope ':username' do
2010-12-31 02:45:03 -05:00
resources :posts
end
2012-09-01 17:08:06 -04:00
```
2010-12-31 02:45:03 -05:00
2012-09-01 21:37:59 -04:00
This will provide you with URLs such as `/bob/posts/1` and will allow you to reference the `username` part of the path as `params[:username]` in controllers, helpers and views.
2010-12-31 02:45:03 -05:00
2012-09-01 17:25:58 -04:00
### Restricting the Routes Created
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
By default, Rails creates routes for the seven 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:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-10-10 10:35:50 -04:00
resources :photos, only: [:index, :show]
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
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.
2010-04-10 04:51:41 -04:00
2012-09-01 21:37:59 -04:00
The `:except` option specifies a route or list of routes that Rails should _not_ create:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-10-10 10:35:50 -04:00
resources :photos, except: :destroy
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
In this case, Rails will create all of the normal routes except the route for `destroy` (a `DELETE` request to `/photos/:id` ).
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
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.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Translated Paths
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
Using `scope` , we can alter path names generated by resources:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
scope(path_names: { new: 'neu', edit: 'bearbeiten' }) do
resources :categories, path: 'kategorien'
2010-04-10 04:51:41 -04:00
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
Rails now creates routes to the `CategoriesController` .
2009-02-05 20:57:02 -05:00
2013-10-31 06:45:09 -04:00
| HTTP Verb | Path | Controller#Action | Named Helper |
| --------- | -------------------------- | ------------------ | ----------------------- |
| GET | /kategorien | categories#index | categories_path |
| GET | /kategorien/neu | categories#new | new_category_path |
| POST | /kategorien | categories#create | categories_path |
| GET | /kategorien/:id | categories#show | category_path(:id) |
| GET | /kategorien/:id/bearbeiten | categories#edit | edit_category_path(:id) |
| PATCH/PUT | /kategorien/:id | categories#update | category_path(:id) |
| DELETE | /kategorien/:id | categories#destroy | category_path(:id) |
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Overriding the Singular Form
2009-02-05 20:57:02 -05:00
2012-12-02 15:52:12 -05:00
If you want to define the singular form of a resource, you should add additional rules to the `Inflector` :
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2010-07-03 04:01:01 -04:00
ActiveSupport::Inflector.inflections do |inflect|
inflect.irregular 'tooth', 'teeth'
end
2012-09-01 17:08:06 -04:00
```
2010-04-10 04:51:41 -04:00
2012-09-01 21:37:59 -04:00
### Using `:as` in Nested Resources
2010-04-10 04:51:41 -04:00
2012-12-02 15:52:12 -05:00
The `:as` option overrides the automatically-generated name for the resource in nested route helpers. For example:
2010-04-10 04:51:41 -04:00
2012-09-01 17:08:06 -04:00
```ruby
2010-04-10 04:51:41 -04:00
resources :magazines do
2012-10-10 10:35:50 -04:00
resources :ads, as: 'periodical_ads'
2010-04-10 04:51:41 -04:00
end
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
This will create routing helpers such as `magazine_periodical_ads_url` and `edit_magazine_periodical_ad_path` .
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
Inspecting and Testing Routes
-----------------------------
2009-02-05 20:57:02 -05:00
2010-04-10 04:51:41 -04:00
Rails offers facilities for inspecting and testing your routes.
2009-02-05 20:57:02 -05:00
2012-12-02 15:16:07 -05:00
### Listing Existing Routes
2009-02-05 20:57:02 -05:00
2012-09-06 22:26:59 -04:00
To get a complete list of the available routes in your application, visit `http://localhost:3000/rails/info/routes` in your browser while your server is running in the **development** environment. You can also execute the `rake routes` command in your terminal to produce the same output.
2012-06-02 12:16:28 -04:00
2012-09-01 21:37:59 -04:00
Both methods will list all of your routes, in the same order that they appear in `routes.rb` . For each route, you'll see:
2009-02-05 20:57:02 -05:00
* The route name (if any)
* The HTTP verb used (if the route doesn't respond to all verbs)
2010-04-10 04:51:41 -04:00
* The URL pattern to match
* The routing parameters for the route
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
For example, here's a small section of the `rake routes` output for a RESTful route:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```
2012-11-05 16:49:17 -05:00
users GET /users(.:format) users#index
2011-07-14 13:54:59 -04:00
POST /users(.:format) users#create
2012-11-05 16:49:17 -05:00
new_user GET /users/new(.:format) users#new
2011-07-14 13:54:59 -04:00
edit_user GET /users/:id/edit(.:format) users#edit
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
You may restrict the listing to the routes that map to a particular controller setting the `CONTROLLER` environment variable:
2010-08-08 12:29:58 -04:00
2012-09-01 20:45:26 -04:00
```bash
2010-08-14 01:13:00 -04:00
$ CONTROLLER=users rake routes
2012-09-01 17:08:06 -04:00
```
2010-08-08 12:29:58 -04:00
2012-09-01 21:37:59 -04:00
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.
2009-02-05 20:57:02 -05:00
2012-09-01 17:25:58 -04:00
### Testing Routes
2009-02-05 20:57:02 -05:00
2012-09-02 01:08:20 -04:00
Routes should be included in your testing strategy (just like the rest of your application). Rails offers three [built-in assertions ](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html ) designed to make testing routes simpler:
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
* `assert_generates`
* `assert_recognizes`
* `assert_routing`
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
#### The `assert_generates` Assertion
2009-02-05 20:57:02 -05:00
2012-12-02 15:52:12 -05:00
`assert_generates` asserts that a particular set of options generate a particular path and can be used with default routes or custom routes. For example:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
assert_generates '/photos/1', { controller: 'photos', action: 'show', id: '1' }
assert_generates '/about', controller: 'pages', action: 'about'
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
#### The `assert_recognizes` Assertion
2009-02-05 20:57:02 -05:00
2012-12-02 15:52:12 -05:00
`assert_recognizes` is the inverse of `assert_generates` . It asserts that a given path is recognized and routes it to a particular spot in your application. For example:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
assert_recognizes({ controller: 'photos', action: 'show', id: '1' }, '/photos/1')
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
You can supply a `:method` argument to specify the HTTP verb:
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
assert_recognizes({ controller: 'photos', action: 'create' }, { path: 'photos', method: :post })
2012-09-01 17:08:06 -04:00
```
2009-02-05 20:57:02 -05:00
2012-09-01 21:37:59 -04:00
#### The `assert_routing` Assertion
2009-02-05 20:57:02 -05:00
2012-12-02 15:52:12 -05:00
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` :
2009-02-05 20:57:02 -05:00
2012-09-01 17:08:06 -04:00
```ruby
2012-11-08 00:36:50 -05:00
assert_routing({ path: 'photos', method: :post }, { controller: 'photos', action: 'create' })
2012-09-01 17:08:06 -04:00
```