diff options
Diffstat (limited to 'guides/source/routing.md')
-rw-r--r-- | guides/source/routing.md | 526 |
1 files changed, 330 insertions, 196 deletions
diff --git a/guides/source/routing.md b/guides/source/routing.md index 469fcf49fb..19784823f7 100644 --- a/guides/source/routing.md +++ b/guides/source/routing.md @@ -1,13 +1,15 @@ 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: +This guide covers the user-facing features of Rails routing. -* Understand the code in `routes.rb` -* Construct your own routes, using either the preferred resourceful style or the `match` method -* Identify what parameters to expect an action to receive -* Automatically create paths and URLs using route helpers -* Use advanced techniques such as constraints and Rack endpoints +After reading this guide, you will know: + +* 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. -------------------------------------------------------------------------------- @@ -18,39 +20,41 @@ The Rails router recognizes URLs and dispatches them to a controller's action. I ### Connecting URLs to Code -When your Rails application receives an incoming request +When your Rails application receives an incoming request for: ``` GET /patients/17 ``` -it asks the router to match it to a controller action. If the first matching route is +it asks the router to match it to a controller action. If the first matching route is: ```ruby -get "/patients/:id" => "patients#show" +get '/patients/:id', to: 'patients#show' ``` -the request is dispatched to the `patients` controller's `show` action with `{ id: "17" }` in `params`. +the request is dispatched to the `patients` controller's `show` action with `{ id: '17' }` in `params`. ### Generating Paths and URLs from Code -You can also generate paths and URLs. If the route above is modified to be +You can also generate paths and URLs. If the route above is modified to be: ```ruby -get "/patients/:id" => "patients#show", as: "patient" +get '/patients/:id', to: 'patients#show', as: 'patient' ``` -If your application contains this code: +and your application contains this code in the controller: ```ruby @patient = Patient.find(17) ``` +and this in the corresponding view: + ```erb -<%= link_to "Patient Record", patient_path(@patient) %> +<%= link_to 'Patient Record', patient_path(@patient) %> ``` -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. +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. Resource Routing: the Rails Default ----------------------------------- @@ -61,23 +65,23 @@ Resource routing allows you to quickly declare all of the common routes for a gi 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. -When your Rails application receives an incoming request for +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 +it asks the router to map it to a controller action. If the first matching route is: ```ruby resources :photos ``` -Rails would dispatch that request to the `destroy` method on the `photos` controller with `{ id: "17" }` in `params`. +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 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 +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: ```ruby resources :photos @@ -85,19 +89,21 @@ resources :photos creates seven different routes in your application, all mapping to the `Photos` controller: -| HTTP Verb | Path | 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 | -| PATCH/PUT | /photos/:id | update | update a specific photo | -| DELETE | /photos/:id | destroy | delete a specific photo | +| 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 | + +NOTE: Because the router uses the HTTP verb and URL to match inbound requests, four URLs map to seven different actions. 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. -### Paths and URLs +### Path and URL Helpers Creating a resourceful route will also expose a number of helpers to the controllers in your application. In the case of `resources :photos`: @@ -108,8 +114,6 @@ Creating a resourceful route will also expose a number of helpers to the control 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`: @@ -118,7 +122,7 @@ If you need to create routes for more than one resource, you can save a bit of t resources :photos, :books, :videos ``` -This works exactly the same as +This works exactly the same as: ```ruby resources :photos @@ -128,13 +132,19 @@ resources :videos ### Singular Resources -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. +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: ```ruby -get "profile" => "users#show" +get 'profile', to: 'users#show' ``` -This resourceful route +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 +``` + +This resourceful route: ```ruby resource :geocoder @@ -142,16 +152,16 @@ resource :geocoder creates six different routes in your application, all mapping to the `Geocoders` controller: -| HTTP Verb | Path | 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 | -| PATCH/PUT | /geocoder | update | update the one and only geocoder resource | -| DELETE | /geocoder | destroy | delete the geocoder resource | +| 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 | -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. +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`). A singular resourceful route generates these helpers: @@ -161,6 +171,12 @@ A singular resourceful route generates these helpers: As with plural resources, the same helpers ending in `_url` will also include the host, port and path prefix. +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: + +```ruby +form_for @geocoder, url: geocoder_path do |f| +``` + ### 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: @@ -173,55 +189,55 @@ end This will create a number of routes for each of the `posts` and `comments` controller. For `Admin::PostsController`, Rails will create: -| HTTP Verb | Path | action | used for | -| --------- | --------------------- | ------- | ------------------------- | -| GET | /admin/posts | index | admin_posts_path | -| GET | /admin/posts/new | new | new_admin_post_path | -| POST | /admin/posts | create | admin_posts_path | -| GET | /admin/posts/:id | show | admin_post_path(:id) | -| GET | /admin/posts/:id/edit | edit | edit_admin_post_path(:id) | -| PATCH/PUT | /admin/posts/:id | update | admin_post_path(:id) | -| DELETE | /admin/posts/:id | destroy | admin_post_path(:id) | +| 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) | -If you want to route `/posts` (without the prefix `/admin`) to `Admin::PostsController`, you could use +If you want to route `/posts` (without the prefix `/admin`) to `Admin::PostsController`, you could use: ```ruby -scope module: "admin" do +scope module: 'admin' do resources :posts, :comments end ``` -or, for a single case +or, for a single case: ```ruby -resources :posts, module: "admin" +resources :posts, module: 'admin' ``` -If you want to route `/admin/posts` to `PostsController` (without the `Admin::` module prefix), you could use +If you want to route `/admin/posts` to `PostsController` (without the `Admin::` module prefix), you could use: ```ruby -scope "/admin" do +scope '/admin' do resources :posts, :comments end ``` -or, for a single case +or, for a single case: ```ruby -resources :posts, path: "/admin/posts" +resources :posts, path: '/admin/posts' ``` 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`: -| HTTP Verb | Path | action | named helper | -| --------- | --------------------- | ------- | ------------------- | -| GET | /admin/posts | index | posts_path | -| GET | /admin/posts/new | new | new_post_path | -| POST | /admin/posts | create | posts_path | -| GET | /admin/posts/:id | show | post_path(:id) | -| GET | /admin/posts/:id/edit | edit | edit_post_path(:id) | -| PATCH/PUT | /admin/posts/:id | update | post_path(:id) | -| DELETE | /admin/posts/:id | destroy | post_path(:id) | +| 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) | ### Nested Resources @@ -247,15 +263,15 @@ end In addition to the routes for magazines, this declaration will also route ads to an `AdsController`. The ad URLs require a magazine: -| HTTP Verb | Path | action | used for | -| --------- | ------------------------------------ | ------- | -------------------------------------------------------------------------- | -| GET | /magazines/:magazine_id/ads | index | display a list of all ads for a specific magazine | -| GET | /magazines/:magazine_id/ads/new | new | return an HTML form for creating a new ad belonging to a specific magazine | -| POST | /magazines/:magazine_id/ads | create | create a new ad belonging to a specific magazine | -| GET | /magazines/:magazine_id/ads/:id | show | display a specific ad belonging to a specific magazine | -| GET | /magazines/:magazine_id/ads/:id/edit | edit | return an HTML form for editing an ad belonging to a specific magazine | -| PATCH/PUT | /magazines/:magazine_id/ads/:id | update | update a specific ad belonging to a specific magazine | -| DELETE | /magazines/:magazine_id/ads/:id | destroy | delete a specific ad belonging to a specific magazine | +| 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 | 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)`). @@ -271,7 +287,7 @@ resources :publishers do end ``` -Deeply-nested resources quickly become cumbersome. In this case, for example, the application would recognize paths such as +Deeply-nested resources quickly become cumbersome. In this case, for example, the application would recognize paths such as: ``` /publishers/1/magazines/2/photos/3 @@ -281,9 +297,94 @@ The corresponding route helper would be `publisher_magazine_photo_url`, requirin TIP: _Resources should never be nested more than 1 level deep._ +#### 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 +``` + +There exists two options for `scope` to customize shallow routes. `:shallow_path` prefixes member paths with the specified parameter: + +```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: + +| 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 | + +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: + +| 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 | + ### Routing concerns -Routing Concerns allows you to declare common routes that can be reused inside others resources and routes. +Routing Concerns allows you to declare common routes that can be reused inside others resources and routes. To define a concern: ```ruby concern :commentable do @@ -295,7 +396,7 @@ concern :image_attachable do end ``` -These concerns can be used in resources to avoid code duplication and share behavior across routes. +These concerns can be used in resources to avoid code duplication and share behavior across routes: ```ruby resources :messages, concerns: :commentable @@ -303,6 +404,19 @@ resources :messages, concerns: :commentable resources :posts, concerns: [:commentable, :image_attachable] ``` +The above is equivalent to: + +```ruby +resources :messages do + resources :comments +end + +resources :posts do + resources :comments + resources :images, only: :index +end +``` + Also you can use them in any place that you want inside the routes, for example in a scope or namespace call: ```ruby @@ -321,34 +435,34 @@ resources :magazines do end ``` -When using `magazine_ad_path`, you can pass in instances of `Magazine` and `Ad` instead of the numeric IDs. +When using `magazine_ad_path`, you can pass in instances of `Magazine` and `Ad` instead of the numeric IDs: ```erb -<%= link_to "Ad details", magazine_ad_path(@magazine, @ad) %> +<%= 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: ```erb -<%= link_to "Ad details", url_for([@magazine, @ad]) %> +<%= 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: ```erb -<%= link_to "Ad details", [@magazine, @ad] %> +<%= link_to 'Ad details', [@magazine, @ad] %> ``` If you wanted to link to just a magazine: ```erb -<%= link_to "Magazine details", @magazine %> +<%= link_to 'Magazine details', @magazine %> ``` For other actions, you just need to insert the action name as the first element of the array: ```erb -<%= link_to "Edit Ad", [:edit, @magazine, @ad] %> +<%= link_to 'Edit Ad', [:edit, @magazine, @ad] %> ``` This allows you to treat instances of your models as URLs, and is a key advantage to using the resourceful style. @@ -369,9 +483,12 @@ resources :photos do 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. +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. -Within the block of member routes, each route name specifies the HTTP verb that it will recognize. 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: +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: ```ruby resources :photos do @@ -379,6 +496,8 @@ resources :photos do end ``` +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]`. + #### Adding Collection Routes To add a route to the collection: @@ -413,9 +532,7 @@ 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. -#### 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. +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. Non-Resourceful Routes ---------------------- @@ -428,7 +545,7 @@ In particular, simple routing makes it very easy to map legacy URLs to new Rails ### 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: +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: ```ruby get ':controller(/:action(/:id))' @@ -452,17 +569,17 @@ NOTE: You can't use `:namespace` or `:module` with a `:controller` path segment. get ':controller(/:action(/:id))', controller: /admin\/[^\/]+/ ``` -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. +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. ### Static Segments -You can specify static segments when creating a route: +You can specify static segments when creating a route by not prepending a colon to a fragment: ```ruby get ':controller/:action/:id/with_user/:user_id' ``` -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" }`. +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' }`. ### The Query String @@ -472,14 +589,14 @@ The `params` will also include any parameters from the query string. For example get ':controller/:action/:id' ``` -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" }`. +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' }`. ### Defining Defaults You do not need to explicitly use the `:controller` and `:action` symbols within a route. You can supply them as defaults: ```ruby -get 'photos/:id' => 'photos#show' +get 'photos/:id', to: 'photos#show' ``` With this route, Rails will match an incoming path of `/photos/12` to the `show` action of `PhotosController`. @@ -487,17 +604,17 @@ With this route, Rails will match an incoming path of `/photos/12` to the `show` 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: ```ruby -get 'photos/:id' => 'photos#show', defaults: { format: 'jpg' } +get 'photos/:id', to: '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. +You can specify a name for any route using the `:as` option: ```ruby -get 'exit' => 'sessions#destroy', as: :logout +get 'exit', to: 'sessions#destroy', as: :logout ``` This will create `logout_path` and `logout_url` as named helpers in your application. Calling `logout_path` will return `/exit` @@ -505,7 +622,7 @@ This will create `logout_path` and `logout_url` as named helpers in your applica You can also use this to override routing methods defined by resources, like this: ```ruby -get ':username', to: "users#show", as: :user +get ':username', to: 'users#show', as: :user ``` 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`. @@ -515,35 +632,35 @@ This will define a `user_path` method that will be available in controllers, hel 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: ```ruby -match 'photos' => 'photos#show', via: [:get, :post] +match 'photos', to: 'photos#show', via: [:get, :post] ``` You can match all verbs to a particular route using `via: :all`: ```ruby -match 'photos' => 'photos#show', via: :all +match 'photos', to: 'photos#show', via: :all ``` -You should avoid routing all verbs to an action unless you have a good reason to, as routing both `GET` requests and `POST` requests to a single action has security implications. +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. ### Segment Constraints You can use the `:constraints` option to enforce a format for a dynamic segment: ```ruby -get 'photos/:id' => 'photos#show', constraints: { id: /[A-Z]\d{5}/ } +get 'photos/:id', to: 'photos#show', constraints: { id: /[A-Z]\d{5}/ } ``` -This route would match paths such as `/photos/A12345`. You can more succinctly express the same route this way: +This route would match paths such as `/photos/A12345`, but not `/photos/893`. You can more succinctly express the same route this way: ```ruby -get 'photos/:id' => 'photos#show', id: /[A-Z]\d{5}/ +get 'photos/:id', to: 'photos#show', id: /[A-Z]\d{5}/ ``` `:constraints` takes regular expressions with the restriction that regexp anchors can't be used. For example, the following route will not work: ```ruby -get '/:id' => 'posts#show', constraints: {id: /^\d/} +get '/:id', to: 'posts#show', constraints: {id: /^\d/} ``` However, note that you don't need to use anchors because all routes are anchored at the start. @@ -551,8 +668,8 @@ However, note that you don't need to use anchors because all routes are anchored 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: ```ruby -get '/:id' => 'posts#show', constraints: { id: /\d.+/ } -get '/:username' => 'users#show' +get '/:id', to: 'posts#show', constraints: { id: /\d.+/ } +get '/:username', to: 'users#show' ``` ### Request-Based Constraints @@ -562,14 +679,14 @@ You can also constrain a route based on any method on the <a href="action_contro You specify a request-based constraint the same way that you specify a segment constraint: ```ruby -get "photos", constraints: {subdomain: "admin"} +get 'photos', constraints: {subdomain: 'admin'} ``` You can also specify constraints in a block form: ```ruby namespace :admin do - constraints subdomain: "admin" do + constraints subdomain: 'admin' do resources :photos end end @@ -591,7 +708,7 @@ class BlacklistConstraint end TwitterClone::Application.routes.draw do - get "*path" => "blacklist#index", + get '*path', to: 'blacklist#index', constraints: BlacklistConstraint.new end ``` @@ -600,55 +717,49 @@ You can also specify constraints as a lambda: ```ruby TwitterClone::Application.routes.draw do - get "*path" => "blacklist#index", + get '*path', to: 'blacklist#index', constraints: lambda { |request| Blacklist.retrieve_ips.include?(request.remote_ip) } end ``` Both the `matches?` method and the lambda gets the `request` object as an argument. -### Route Globbing +### Route Globbing and Wildcard Segments -Route globbing is a way to specify that a particular parameter should be matched to all the remaining parts of a route. For example +Route globbing is a way to specify that a particular parameter should be matched to all the remaining parts of a route. For example: ```ruby -get 'photos/*other' => 'photos#unknown' +get 'photos/*other', to: 'photos#unknown' ``` -This route would match `photos/12` or `/photos/long/path/to/12`, setting `params[:other]` to `"12"` or `"long/path/to/12"`. +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". -Wildcard segments can occur anywhere in a route. For example, +Wildcard segments can occur anywhere in a route. For example: ```ruby -get 'books/*section/:title' => 'books#show' +get 'books/*section/:title', to: 'books#show' ``` -would match `books/some/section/last-words-a-memoir` with `params[:section]` equals `"some/section"`, and `params[:title]` equals `"last-words-a-memoir"`. +would match `books/some/section/last-words-a-memoir` with `params[:section]` equals `'some/section'`, and `params[:title]` equals `'last-words-a-memoir'`. -Technically a route can have even more than one wildcard segment. The matcher assigns segments to parameters in an intuitive way. For example, +Technically, a route can have even more than one wildcard segment. The matcher assigns segments to parameters in an intuitive way. For example: ```ruby -get '*a/foo/*b' => 'test#index' +get '*a/foo/*b', to: 'test#index' ``` -would match `zoo/woo/foo/bar/baz` with `params[:a]` equals `"zoo/woo"`, and `params[:b]` equals `"bar/baz"`. - -NOTE: Starting from Rails 3.1, wildcard routes will always match the optional format segment by default. For example if you have this route: - -```ruby -get '*pages' => 'pages#show' -``` +would match `zoo/woo/foo/bar/baz` with `params[:a]` equals `'zoo/woo'`, and `params[:b]` equals `'bar/baz'`. -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: +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: ```ruby -get '*pages' => 'pages#show', format: false +get '*pages', to: 'pages#show', format: false ``` NOTE: If you want to make the format segment mandatory, so it cannot be omitted, you can supply `format: true` like this: ```ruby -get '*pages' => 'pages#show', format: true +get '*pages', to: 'pages#show', format: true ``` ### Redirection @@ -656,20 +767,20 @@ get '*pages' => 'pages#show', format: true You can redirect any path to another path using the `redirect` helper in your router: ```ruby -get "/stories" => redirect("/posts") +get '/stories', to: redirect('/posts') ``` You can also reuse dynamic segments from the match in the path to redirect to: ```ruby -get "/stories/:name" => redirect("/posts/%{name}") +get '/stories/:name', to: redirect('/posts/%{name}') ``` -You can also provide a block to redirect, which receives the params and the request object: +You can also provide a block to redirect, which receives the symbolized path parameters and the request object: ```ruby -get "/stories/:name" => redirect {|params, req| "/posts/#{params[:name].pluralize}" } -get "/stories" => redirect {|p, req| "/posts/#{req.subdomain}" } +get '/stories/:name', to: redirect {|path_params, req| "/posts/#{path_params[:name].pluralize}" } +get '/stories', to: redirect {|path_params, req| "/posts/#{req.subdomain}" } ``` 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. @@ -678,35 +789,45 @@ In all of these cases, if you don't provide the leading host (`http://www.exampl ### Routing to Rack Applications -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. +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: ```ruby -match "/application.js" => Sprockets, via: :all +match '/application.js', to: Sprockets, via: :all ``` 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. -NOTE: For the curious, `"posts#index"` actually expands out to `PostsController.action(:index)`, which returns a valid Rack application. +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: +You can specify what Rails should route `'/'` to with the `root` method: ```ruby root to: 'pages#main' root 'pages#main' # shortcut for the above ``` -You should put the `root` route at the top of the file, because it is the most popular route and should be matched first. You also need to delete the `public/index.html` file for the root route to take effect. +You should put the `root` route at the top of the file, because it is the most popular route and should be matched first. NOTE: The `root` route only routes `GET` requests to the action. +You can also use root inside namespaces and scopes as well. For example: + +```ruby +namespace :admin do + root to: "admin#index" +end + +root to: "home#index" +``` + ### Unicode character routes -You can specify unicode character routes directly. For example +You can specify unicode character routes directly. For example: ```ruby -match 'こんにちは' => 'welcome#index' +get 'こんにちは', to: 'welcome#index' ``` Customizing Resourceful Routes @@ -719,23 +840,36 @@ While the default routes and helpers generated by `resources :posts` will usuall The `:controller` option lets you explicitly specify a controller to use for the resource. For example: ```ruby -resources :photos, controller: "images" +resources :photos, controller: 'images' ``` will recognize incoming paths beginning with `/photos` but route to the `Images` controller: -| HTTP Verb | Path | action | named helper | -| --------- | ---------------- | ------- | -------------------- | -| GET | /photos | index | photos_path | -| GET | /photos/new | new | new_photo_path | -| POST | /photos | create | photos_path | -| GET | /photos/:id | show | photo_path(:id) | -| GET | /photos/:id/edit | edit | edit_photo_path(:id) | -| PATCH/PUT | /photos/:id | update | photo_path(:id) | -| DELETE | /photos/:id | destroy | photo_path(:id) | +| 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) | NOTE: Use `photos_path`, `new_photo_path`, etc. to generate paths for this resource. +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. + +NOTE: Only the directory notation is supported. Specifying the +controller with Ruby constant notation (eg. `controller: 'Admin::UserPermissions'`) +can lead to routing problems and results in +a warning. + ### Specifying Constraints You can use the `:constraints` option to specify a required format on the implicit `id`. For example: @@ -764,20 +898,20 @@ TIP: By default the `:id` parameter doesn't accept dots - this is because the do The `:as` option lets you override the normal naming for the named route helpers. For example: ```ruby -resources :photos, as: "images" +resources :photos, as: 'images' ``` 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. -| HTTP Verb | Path | action | named helper | -| --------- | ---------------- | ------- | -------------------- | -| GET | /photos | index | images_path | -| GET | /photos/new | new | new_image_path | -| POST | /photos | create | images_path | -| GET | /photos/:id | show | image_path(:id) | -| GET | /photos/:id/edit | edit | edit_image_path(:id) | -| PATCH/PUT | /photos/:id | update | image_path(:id) | -| DELETE | /photos/:id | destroy | image_path(:id) | +| 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) | ### Overriding the `new` and `edit` Segments @@ -787,7 +921,7 @@ The `:path_names` option lets you override the automatically-generated "new" and resources :photos, path_names: { new: 'make', edit: 'change' } ``` -This would cause the routing to recognize paths such as +This would cause the routing to recognize paths such as: ``` /photos/make @@ -799,18 +933,18 @@ NOTE: The actual action names aren't changed by this option. The two paths shown TIP: If you find yourself wanting to change this option uniformly for all of your routes, you can use a scope. ```ruby -scope path_names: { new: "make" } do +scope path_names: { new: 'make' } do # rest of your routes end ``` ### Prefixing the Named Route Helpers -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. +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: ```ruby -scope "admin" do - resources :photos, as: "admin_photos" +scope 'admin' do + resources :photos, as: 'admin_photos' end resources :photos @@ -821,7 +955,7 @@ This will provide route helpers such as `admin_photos_path`, `new_admin_photo_pa To prefix a group of route helpers, use `:as` with `scope`: ```ruby -scope "admin", as: "admin" do +scope 'admin', as: 'admin' do resources :photos, :accounts end @@ -835,7 +969,7 @@ NOTE: The `namespace` scope will automatically add `:as` as well as `:module` an You can prefix routes with a named parameter also: ```ruby -scope ":username" do +scope ':username' do resources :posts end ``` @@ -867,26 +1001,26 @@ TIP: If your application has many RESTful routes, using `:only` and `:except` to Using `scope`, we can alter path names generated by resources: ```ruby -scope(path_names: { new: "neu", edit: "bearbeiten" }) do - resources :categories, path: "kategorien" +scope(path_names: { new: 'neu', edit: 'bearbeiten' }) do + resources :categories, path: 'kategorien' end ``` Rails now creates routes to the `CategoriesController`. -| HTTP Verb | Path | action | used for | -| --------- | -------------------------- | ------- | ----------------------- | -| GET | /kategorien | index | categories_path | -| GET | /kategorien/neu | new | new_category_path | -| POST | /kategorien | create | categories_path | -| GET | /kategorien/:id | show | category_path(:id) | -| GET | /kategorien/:id/bearbeiten | edit | edit_category_path(:id) | -| PATCH/PUT | /kategorien/:id | update | category_path(:id) | -| DELETE | /kategorien/:id | destroy | category_path(:id) | +| 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) | ### Overriding the Singular Form -If you want to define the singular form of a resource, you should add additional rules to the `Inflector`. +If you want to define the singular form of a resource, you should add additional rules to the `Inflector`: ```ruby ActiveSupport::Inflector.inflections do |inflect| @@ -896,7 +1030,7 @@ end ### Using `:as` in Nested Resources -The `:as` option overrides the automatically-generated name for the resource in nested route helpers. For example, +The `:as` option overrides the automatically-generated name for the resource in nested route helpers. For example: ```ruby resources :magazines do @@ -911,7 +1045,7 @@ Inspecting and Testing Routes Rails offers facilities for inspecting and testing your routes. -### Seeing Existing Routes +### Listing Existing Routes 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. @@ -949,31 +1083,31 @@ Routes should be included in your testing strategy (just like the rest of your a #### The `assert_generates` Assertion -`assert_generates` asserts that a particular set of options generate a particular path and can be used with default routes or custom routes. +`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: ```ruby -assert_generates "/photos/1", { controller: "photos", action: "show", id: "1" } -assert_generates "/about", controller: "pages", action: "about" +assert_generates '/photos/1', { controller: 'photos', action: 'show', id: '1' } +assert_generates '/about', controller: 'pages', action: 'about' ``` #### The `assert_recognizes` Assertion -`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. +`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: ```ruby -assert_recognizes({ controller: "photos", action: "show", id: "1" }, "/photos/1") +assert_recognizes({ controller: 'photos', action: 'show', id: '1' }, '/photos/1') ``` You can supply a `:method` argument to specify the HTTP verb: ```ruby -assert_recognizes({ controller: "photos", action: "create" }, { path: "photos", method: :post }) +assert_recognizes({ controller: 'photos', action: 'create' }, { 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`. +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`: ```ruby -assert_routing({ path: "photos", method: :post }, { controller: "photos", action: "create" }) +assert_routing({ path: 'photos', method: :post }, { controller: 'photos', action: 'create' }) ``` |