Rails Routing from the Outside In
This guide covers the user-facing features of Rails routing.
After reading this guide, you will know:
- How to interpret the code in
config/routes.rb
. - How to construct your own routes, using either the preferred resourceful style or the
match
method. - How to declare route parameters, which are passed onto controller actions.
- How to automatically create paths and URLs using route helpers.
- Advanced techniques such as creating constraints and mounting Rack endpoints.
1. The Purpose of the Rails Router
The Rails router matches incoming HTTP requests to specific controller actionsin your Rails application based on the URL path. (It can also forward to aRack application.) The router also generates path and URLhelpers based on the resources configured in the router.
1.1. Routing Incoming URLs to Code
When your Rails application receives an incoming request, it asks the router to match it to a controller action (aka method). For example, take the following incoming request:
GET /users/17
If the first matching route is:
get"/users/:id",to:"users#show"
The request is matched to theUsersController
class'sshow
action with{ id: '17' }
in theparams
hash.
Theto:
option expects acontroller#action
format when passed a string. Alternatively, You can pass a symbol and use theaction:
option, instead ofto:
. You can also pass a string without a#
, in which case thecontroller:
option is used instead toto:
. For example:
get"/users/:id",controller:"users",action: :show
Rails uses snake_case for controller names when specifying routes. For example, if you have a controller namedUserProfilesController
, you would specify a route to the show action asuser_profiles#show
.
1.2. Generating Paths and URLs from Code
The Router automatically generates path and URL helper methods for your application. With these methods you can avoid hard-coded path and URL strings.
For example, theuser_path
anduser_url
helper methods are available when defining the following route:
get"/users/:id",to:"users#show",as:"user"
Theas:
option is used to provide a custom name for a route, which is used when generating URL and path helpers.
Assuming your application contains this code in the controller:
@user=User.find(params[:id])
and this in the corresponding view:
<%=link_to'User Record',user_path(@user)%>
The router will generate the path/users/17
fromuser_path(@user)
. Using theuser_path
helper allows you to avoid having to hard-code a path in your views. This is helpful if you eventually move the route to a different URL, as you won't need to update the corresponding views.
It also generatesuser_url
, which has a similar purpose. Whileuser_path
generates a relative URL like/users/17
,user_url
generates an absolute URL such ashttps://example.com/users/17
in the above example.
1.3. Configuring the Rails Router
Routes live inconfig/routes.rb
. Here is an example of what routes look like in a typical Rails application. The sections that follow will explain the different route helpers used in this file:
Rails.application.routes.drawdoresources:brands,only:[:index,:show]doresources:products,only:[:index,:show]endresource:basket,only:[:show,:update,:destroy]resolve("Basket"){route_for(:basket)}end
Since this is a regular Ruby source file, you can use all of Ruby's features (like conditionals and loops) to help you define your routes.
TheRails.application.routes.draw do ... end
block that wraps your route definitions is required to establish the scope for the router DSL (Domain Specific Language) and must not be deleted.
Be careful with variable names inroutes.rb
as they can clash with the DSL methods of the router.
2. Resource Routing: the Rails Default
Resource routing allows you to quickly declare all of the common routes for a given resource controller. For example, a single call toresources
declares all of the necessary routes for theindex
,show
,new
,edit
,create
,update
, anddestroy
actions, without you having to declare each route separately.
2.1. Resources on the Web
Browsers request pages from Rails by making a request for a URL using a specific HTTP verb, such asGET
,POST
,PATCH
,PUT
, andDELETE
. Each HTTP verb is a request to perform an operation on the resource. A resource route maps related requests to actions in a single controller.
When your Rails application receives an incoming request for:
DELETE /photos/17
it asks the router to map it to a controller action. If the first matching route is:
resources:photos
Rails would dispatch that request to thedestroy
action on thePhotosController
with{ id: '17' }
inparams
.
2.2. CRUD, Verbs, and Actions
In Rails, resourceful routes provide a mapping from incoming requests (acombination of HTTP verb + URL) to controller actions. By convention, eachaction generally maps to a specificCRUD operation on your data. A single entry inthe routing file, such as:
resources:photos
creates seven different routes in your application, all mapping to thePhotosController
actions:
HTTP Verb | Path | Controller#Action | Used to |
---|---|---|---|
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 |
Since the router uses the HTTP verband path to match inbound requests, four URLs can map to seven different controller actions. For example, the samephotos/
path matches tophotos#index
when the verb isGET
andphotos#create
when the verb isPOST
.
Order matters in theroutes.rb
file. Rails routes are matched in the order they are specified. For example, if you have aresources :photos
above aget 'photos/poll'
theshow
action's route for theresources
line will be matched before theget
line. If you want thephotos/poll
route to match first, you'll need to move theget
lineabove theresources
line.
2.3. Path and URL Helpers
Creating a resourceful route will also expose a number of helpers to controllers and views in your application.
For example, addingresources :photos
to the route file will generate these_path
helpers:
Path Helper | Returns URL |
---|---|
photos_path | /photos |
new_photo_path | /photos/new |
edit_photo_path(:id) | /photos/:id/edit` |
photo_path(:id) | /photos/:id |
Parameters to the path helpers, such as:id
above, are passed to the generated URL, such thatedit_photo_path(10)
will return/photos/10/edit
.
Each of these_path
helpers also have a corresponding_url
helper (such asphotos_url
) which returns the same path prefixed with the current host, port, and path prefix.
The prefix used before "_path" and "_url" is the route name and can be identified by looking at the "prefix" column of thebin/rails routes
command output. To learn more seeListing Existing Routes below.
2.4. 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 toresources
:
resources:photos,:books,:videos
The above is a shortcut for:
resources:photosresources:booksresources:videos
2.5. Singular Resources
Sometimes, you have a resource that users expect to have only one (i.e. it does not make sense to have anindex
action to list all values of that resource). In that case, you can useresource
(singular) instead ofresources
.
The below resourceful route creates six routes in your application, all mapping to theGeocoders
controller:
resource:geocoderresolve("Geocoder"){[:geocoder]}
The call toresolve
is necessary for converting instances of theGeocoder
to singular routes throughrecord identification.
Here are all of the routes created for a singular resource:
HTTP Verb | Path | Controller#Action | Used to |
---|---|---|---|
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 |
Singular resources map to plural controllers. For example, thegeocoder
resource maps to theGeocodersController
.
A singular resourceful route generates these helpers:
new_geocoder_path
returns/geocoder/new
edit_geocoder_path
returns/geocoder/edit
geocoder_path
returns/geocoder
As with plural resources, the same helpers ending in_url
will also include the host, port, and path prefix.
2.6. Controller Namespaces and Routing
In large applications, you may wish to organize groups of controllers under a namespace. For example, you may have a number of controllers under anAdmin::
namespace, which are inside theapp/controllers/admin
directory. You can route to such a group by using anamespace
block:
namespace:admindoresources:articlesend
ForAdmin::ArticlesController
, Rails will create the following routes:
HTTP Verb | Path | Controller#Action | Named Route Helper |
---|---|---|---|
GET | /admin/articles | admin/articles#index | admin_articles_path |
GET | /admin/articles/new | admin/articles#new | new_admin_article_path |
POST | /admin/articles | admin/articles#create | admin_articles_path |
GET | /admin/articles/:id | admin/articles#show | admin_article_path(:id) |
GET | /admin/articles/:id/edit | admin/articles#edit | edit_admin_article_path(:id) |
PATCH/PUT | /admin/articles/:id | admin/articles#update | admin_article_path(:id) |
DELETE | /admin/articles/:id | admin/articles#destroy | admin_article_path(:id) |
Note that in the above example all of the paths have a/admin
prefix per the default convention fornamespace
.
2.6.1. Using Module
If you want to route/articles
(without the prefix/admin
) toAdmin::ArticlesController
, you can specify the module with ascope
block:
scopemodule:"admin"doresources:articlesend
Another way to write the above:
resources:articles,module:"admin"
2.6.2. Using Scope
Alternatively, you can also route/admin/articles
toArticlesController
(without theAdmin::
module prefix). You can specify the path with ascope
block:
scope"/admin"doresources:articlesend
Another way to write the above:
resources:articles,path:"/admin/articles"
For these alternatives (without/admin
in path and withoutAdmin::
in module prefix), the named route helpers remain the same as if you did not usescope
.
In the last case, the following paths map toArticlesController
:
HTTP Verb | Path | Controller#Action | Named Route Helper |
---|---|---|---|
GET | /admin/articles | articles#index | articles_path |
GET | /admin/articles/new | articles#new | new_article_path |
POST | /admin/articles | articles#create | articles_path |
GET | /admin/articles/:id | articles#show | article_path(:id) |
GET | /admin/articles/:id/edit | articles#edit | edit_article_path(:id) |
PATCH/PUT | /admin/articles/:id | articles#update | article_path(:id) |
DELETE | /admin/articles/:id | articles#destroy | article_path(:id) |
If you need to use a different controller namespace inside anamespace
block you can specify an absolute controller path, e.g:get '/foo', to: '/foo#index'
.
2.7. Nested Resources
It's common to have resources that are logically children of other resources. For example, suppose your application includes these models:
classMagazine<ApplicationRecordhas_many:adsendclassAd<ApplicationRecordbelongs_to:magazineend
Nested route declarations allow you to capture this relationship in your routing:
resources:magazinesdoresources:adsend
In addition to the routes for magazines, this declaration will also route ads to anAdsController
. Here are all of the routes for the nestedads
resource:
HTTP Verb | Path | Controller#Action | Used to |
---|---|---|---|
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 the usual path and url routing helpers such asmagazine_ads_url
andedit_magazine_ad_path
. Since theads
resource is nested belowmagazines
, The ad URLs require a magazine. The helpers can take an instance ofMagazine
as the first parameter (edit_magazine_ad_path(@magazine, @ad)
).
2.7.1. Limits to Nesting
You can nest resources within other nested resources if you like. For example:
resources:publishersdoresources:magazinesdoresources:photosendend
In the above example, the application would recognize paths such as:
/publishers/1/magazines/2/photos/3
The corresponding route helper would bepublisher_magazine_photo_url
, requiring you to specify objects at all three levels. As you can see, deeply nested resources can become overly complex and cumbersome to maintain.
The general rule of thumb is to only nest resources 1 level deep.
2.7.2. Shallow Nesting
One way to avoid deep nesting (as recommended above) is to generate thecollection actions scoped under the parent - so as to get a sense of thehierarchy, but to not nest the member actions. In other words, to only buildroutes with the minimal amount of information to uniquely identify the resource.
The "member" actions are the ones that apply to an individual resource and require an ID to identify the specific resource they are acting upon, such asshow
,edit
, etc. The "collection" actions are the ones that act on the entire set of the resource, such asindex
.
For example:
resources:articlesdoresources:comments,only:[:index,:new,:create]endresources:comments,only:[:show,:edit,:update,:destroy]
Above we use the:only
option which tells Rails to create only the specified routes. This idea strikes a balance between descriptive routes and deep nesting. There is a shorthand syntax to achieve just that, via the:shallow
option:
resources:articlesdoresources:comments,shallow:trueend
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:
resources:articles,shallow:truedoresources:commentsresources:quotesend
The articles resource above will generate the following routes:
HTTP Verb | Path | Controller#Action | Named Route Helper |
---|---|---|---|
GET | /articles/:article_id/comments(.:format) | comments#index | article_comments_path |
POST | /articles/:article_id/comments(.:format) | comments#create | article_comments_path |
GET | /articles/:article_id/comments/new(.:format) | comments#new | new_article_comment_path |
GET | /comments/:id/edit(.:format) | comments#edit | edit_comment_path |
GET | /comments/:id(.:format) | comments#show | comment_path |
PATCH/PUT | /comments/:id(.:format) | comments#update | comment_path |
DELETE | /comments/:id(.:format) | comments#destroy | comment_path |
GET | /articles/:article_id/quotes(.:format) | quotes#index | article_quotes_path |
POST | /articles/:article_id/quotes(.:format) | quotes#create | article_quotes_path |
GET | /articles/:article_id/quotes/new(.:format) | quotes#new | new_article_quote_path |
GET | /quotes/:id/edit(.:format) | quotes#edit | edit_quote_path |
GET | /quotes/:id(.:format) | quotes#show | quote_path |
PATCH/PUT | /quotes/:id(.:format) | quotes#update | quote_path |
DELETE | /quotes/:id(.:format) | quotes#destroy | quote_path |
GET | /articles(.:format) | articles#index | articles_path |
POST | /articles(.:format) | articles#create | articles_path |
GET | /articles/new(.:format) | articles#new | new_article_path |
GET | /articles/:id/edit(.:format) | articles#edit | edit_article_path |
GET | /articles/:id(.:format) | articles#show | article_path |
PATCH/PUT | /articles/:id(.:format) | articles#update | article_path |
DELETE | /articles/:id(.:format) | articles#destroy | article_path |
Theshallow
method with a block creates a scope inside of which every nesting is shallow. This generates the same routes as the previous example:
shallowdoresources:articlesdoresources:commentsresources:quotesendend
There are two options that can be used withscope
to customize shallow routes -:shallow_path
and:shallow_prefix
.
Theshallow_path
option prefixes member paths with the given parameter:
scopeshallow_path:"sekret"doresources:articlesdoresources:comments,shallow:trueendend
The comments resource here will have the following routes generated for it:
HTTP Verb | Path | Controller#Action | Named Route Helper |
---|---|---|---|
GET | /articles/:article_id/comments(.:format) | comments#index | article_comments_path |
POST | /articles/:article_id/comments(.:format) | comments#create | article_comments_path |
GET | /articles/:article_id/comments/new(.:format) | comments#new | new_article_comment_path |
GET | /sekret/comments/:id/edit(.:format) | comments#edit | edit_comment_path |
GET | /sekret/comments/:id(.:format) | comments#show | comment_path |
PATCH/PUT | /sekret/comments/:id(.:format) | comments#update | comment_path |
DELETE | /sekret/comments/:id(.:format) | comments#destroy | comment_path |
The:shallow_prefix
option adds the specified parameter to the_path
and_url
route helpers:
scopeshallow_prefix:"sekret"doresources:articlesdoresources:comments,shallow:trueendend
The comments resource here will have the following routes generated for it:
HTTP Verb | Path | Controller#Action | Named Route Helper |
---|---|---|---|
GET | /articles/:article_id/comments(.:format) | comments#index | article_comments_path |
POST | /articles/:article_id/comments(.:format) | comments#create | article_comments_path |
GET | /articles/:article_id/comments/new(.:format) | comments#new | new_article_comment_path |
GET | /comments/:id/edit(.:format) | comments#edit | edit_sekret_comment_path |
GET | /comments/:id(.:format) | comments#show | sekret_comment_path |
PATCH/PUT | /comments/:id(.:format) | comments#update | sekret_comment_path |
DELETE | /comments/:id(.:format) | comments#destroy | sekret_comment_path |
2.8. Routing Concerns
Routing concerns allow you to declare common routes that can be reused inside other resources. To define a concern, use aconcern
block:
concern:commentabledoresources:commentsendconcern:image_attachabledoresources:images,only: :indexend
These concerns can be used in resources to avoid code duplication and share behavior across routes:
resources:messages,concerns: :commentableresources:articles,concerns:[:commentable,:image_attachable]
The above is equivalent to:
resources:messagesdoresources:commentsendresources:articlesdoresources:commentsresources:images,only: :indexend
You can also callconcerns
in ascope
ornamespace
block to get the same result as above. For example:
namespace:messagesdoconcerns:commentableendnamespace:articlesdoconcerns:commentableconcerns:image_attachableend
2.9. Creating Paths and URLs from Objects
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:
resources:magazinesdoresources:adsend
When usingmagazine_ad_path
, you can pass in instances ofMagazine
andAd
instead of the numeric IDs:
<%=link_to'Ad details',magazine_ad_path(@magazine,@ad)%>
The generated path will be something like/magazines/5/ads/42
.
You can also useurl_for
with an array of objects to get the above path, like this:
<%=link_to'Ad details',url_for([@magazine,@ad])%>
In this case, Rails will see that@magazine
is aMagazine
and@ad
is anAd
and will therefore use themagazine_ad_path
helper. An even shorter way to write thatlink_to
is to specify just the object instead of the fullurl_for
call:
<%=link_to'Ad details',[@magazine,@ad]%>
If you wanted to link to just a magazine:
<%=link_to'Magazine details',@magazine%>
For other actions, you need to insert the action name as the first element of the array, foredit_magazine_ad_path
:
<%=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.
In order to automatically derive paths and URLs from objects such as[@magazine, @ad]
, Rails uses methods fromActiveModel::Naming
andActiveModel::Conversion
modules. Specifically, the@magazine.model_name.route_key
returnsmagazines
and@magazine.to_param
returns a string representation of the model'sid
. So the generated path may be something like/magazines/1/ads/42
for the objects[@magazine, @ad]
.
2.10. Adding More RESTful Routes
You are not limited to theseven routes that RESTful routing creates by default. You can add additional routes that apply to the collection or individual members of the collection.
The below sections describe adding member routes and collection routes. The termmember
refers to routes acting on a single element, such asshow
,update
, ordestroy
. The termcollection
refers to routes acting on multiple, or a collection of, elements, such as theindex
route.
2.10.1. Adding Member Routes
You can add amember
block into the resource block like this:
resources:photosdomemberdoget"preview"endend
An incoming GET request to/photos/1/preview
will route to thepreview
action ofPhotosController
. The resource id value will be available inparams[:id]
. It will also create thepreview_photo_url
andpreview_photo_path
helpers.
Within themember
block, each route definition specifies the HTTP verb (get
in the above example withget 'preview'
). In addition toget
, you canusepatch
,put
,post
, ordelete
.
If you don't have multiplemember
routes, you can alsopass:on
to a route, eliminating the block:
resources:photosdoget"preview",on: :memberend
You can also leave out the:on
option, this will create the same member route except that the resource id value will be available inparams[:photo_id]
instead ofparams[:id]
. Route helpers will also be renamed frompreview_photo_url
andpreview_photo_path
tophoto_preview_url
andphoto_preview_path
.
2.10.2. Adding Collection Routes
To add a route to the collection, use acollection
block:
resources:photosdocollectiondoget"search"endend
This will enable Rails to recognize paths such as/photos/search
with GET, and route to thesearch
action ofPhotosController
. It will also create thesearch_photos_url
andsearch_photos_path
route helpers.
Just as with member routes, you can pass:on
to a route:
resources:photosdoget"search",on: :collectionend
If you're defining additional resource routes with a symbol as the first positional argument, be mindful that it is not equivalent to using a string. Symbols infer controller actions while strings infer paths.
2.10.3. Adding Routes for Additional New Actions
To add an alternate new action using the:on
shortcut:
resources:commentsdoget"preview",on: :newend
This will enable Rails to recognize paths such as/comments/new/preview
with GET, and route to thepreview
action ofCommentsController
. It will also create thepreview_new_comment_url
andpreview_new_comment_path
route helpers.
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.
It is possible to customize the default routes and helpers generated byresources
, seecustomizing resourceful routes section for more.
3. Non-Resourceful Routes
In addition to resourceful routing withresources
, Rails has powerful support for routing arbitrary URLs to actions. You don't get groups of routes automatically generated by resourceful routing. Instead, you set up each route separately within your application.
While you should usually use resourceful routing, there are places where non-resourceful routing is more appropriate. There's no need to try to force every last piece of your application into a resourceful framework if that's not a good fit.
One example use case for non-resourceful routing is mapping existing legacy URLs to new Rails actions.
3.1. 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. For example, consider this route:
get"photos(/:id)",to:"photos#display"
If an incomingGET
request of/photos/1
is processed by this route, then the result will be to invoke thedisplay
action of thePhotosController
, and to make the final parameter"1"
available asparams[:id]
. This route will also route the incoming request of/photos
toPhotosController#display
, since:id
is an optional parameter, denoted by parentheses in the above example.
3.2. Dynamic Segments
You can set up as many dynamic segments within a regular route as you like. Any segment will be available to the action as part ofparams
. If you set up this route:
get"photos/:id/:user_id",to:"photos#show"
This route will respond to paths such as/photos/1/2
. Theparams
hash will be { controller: 'photos', action: 'show', id: '1', user_id: '2' }.
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.
3.3. Static Segments
You can specify static segments when creating a route by not prepending a colon to a segment:
get"photos/:id/with_user/:user_id",to:"photos#show"
This route would respond to paths such as/photos/1/with_user/2
. In this case,params
would be{ controller: 'photos', action: 'show', id: '1', user_id: '2' }
.
3.4. The Query String
Theparams
will also include any parameters from the query string. For example, with this route:
get"photos/:id",to:"photos#show"
An incomingGET
request for/photos/1?user_id=2
will be dispatched to theshow
action of thePhotosController
class as usual and theparams
hash will be{ controller: 'photos', action: 'show', id: '1', user_id: '2' }
.
3.5. Defining Default Parameters
You can define 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:
get"photos/:id",to:"photos#show",defaults:{format:"jpg"}
Rails would matchphotos/12
to theshow
action ofPhotosController
, and setparams[:format]
to"jpg"
.
You can also use adefaults
block to define the defaults for multiple items:
defaultsformat: :jsondoresources:photosresources:articlesend
You cannot override defaults via query parameters - this is for security reasons. The only defaults that can be overridden are dynamic segments via substitution in the URL path.
3.6. Naming Routes
You can specify a name that will be used by the_path
and_url
helpers for any route using the:as
option:
get"exit",to:"sessions#destroy",as: :logout
This will createlogout_path
andlogout_url
as the route helpers in your application. Callinglogout_path
will return/exit
.
You can also useas
to override routing helper names defined byresources
by placing a custom route definitionbefore the resource is defined, like this:
get":username",to:"users#show",as: :userresources:users
This will define auser_path
helper that will match/:username
(e.g./jane
). Inside theshow
action ofUsersController
,params[:username]
will contain the username for the user.
3.7. HTTP Verb Constraints
In general, you should use theget
,post
,put
,patch
, anddelete
methods to constrain a route to a particular verb. There is amatch
method that you could use with the:via
option to match multiple verbs at once:
match"photos",to:"photos#show",via:[:get,:post]
The above route matches GET and POST requests to theshow
action of thePhotosController
.
You can match all verbs to a particular route usingvia: :all
:
match"photos",to:"photos#show",via: :all
Routing bothGET
andPOST
requests to a single action has securityimplications. For example, theGET
action won't check for CSRF token (sowriting to the database fromGET
request is not a good idea. For moreinformation see thesecurity guide). Ingeneral, avoid routing all verbs to a single action unless you have a goodreason.
3.8. Segment Constraints
You can use the:constraints
option to enforce a format for a dynamic segment:
get"photos/:id",to:"photos#show",constraints:{id:/[A-Z]\d{5}/}
The above route definition requiresid
to be 5 alphanumeric characters long. Therefore, this route would match paths such as/photos/A12345
, but not/photos/893
. You can more succinctly express the same route this way:
get"photos/:id",to:"photos#show",id:/[A-Z]\d{5}/
The:constraints
option takes regular expressions (as well as any object that responds tomatches?
method) with the restriction that regexp anchors can't be used. For example, the following route will not work:
get"/:id",to:"articles#show",constraints:{id:/^\d/}
However, note that you don't need to use anchors because all routes are anchored at the start and the end.
For example:
get"/:id",to:"articles#show",constraints:{id:/\d.+/}get"/:username",to:"users#show"
The above routes would allow sharing the root namespace and:
- route paths that always begin with a number, like
/1-hello-world
, toarticles
withid
value. - route paths that never begin with a number, like
/david
, tousers
withusername
value.
3.9. Request-Based Constraints
You can also constrain a route based on any method on theRequest object that returns aString
.
You specify a request-based constraint the same way that you specify a segment constraint. For example:
get"photos",to:"photos#index",constraints:{subdomain:"admin"}
Will match an incoming request with a path toadmin
subdomain.
You can also specify constraints by using aconstraints
block:
constraintssubdomain:"admin"doresources:photosend
Will match something likehttps://admin.example.com/photos
.
Request constraints work by calling a method on theRequest object with the same name as the hash key and then comparing the return value with the hash value. For example:constraints: { subdomain: 'api' }
will match anapi
subdomain as expected. However, using a symbolconstraints: { subdomain: :api }
will not, becauserequest.subdomain
returns'api'
as a String.
Constraint values should match the corresponding Request object method return type.
There is an exception for theformat
constraint, while it's a method on the Request object, it's also an implicit optional parameter on every path. Segment constraints take precedence and theformat
constraint is only applied when enforced through a hash. For example,get 'foo', constraints: { format: 'json' }
will matchGET /foo
because the format is optional by default.
You canuse a lambda like inget 'foo', constraints: lambda { |req| req.format == :json }
to only match the route to explicit JSON requests.
3.10. Advanced Constraints
If you have a more advanced constraint, you can provide an object that responds tomatches?
that Rails should use. Let's say you wanted to route all users on a restricted list to theRestrictedListController
. You could do:
classRestrictedListConstraintdefinitialize@ips=RestrictedList.retrieve_ipsenddefmatches?(request)@ips.include?(request.remote_ip)endendRails.application.routes.drawdoget"*path",to:"restricted_list#index",constraints:RestrictedListConstraint.newend
You can also specify constraints as a lambda:
Rails.application.routes.drawdoget"*path",to:"restricted_list#index",constraints:lambda{|request|RestrictedList.retrieve_ips.include?(request.remote_ip)}end
Both thematches?
method and the lambda gets therequest
object as an argument.
3.10.1. Constraints in a Block Form
You can specify constraints in a block form. This is useful for when you need to apply the same rule to several routes. For example:
classRestrictedListConstraint# ...Same as the example aboveendRails.application.routes.drawdoconstraints(RestrictedListConstraint.new)doget"*path",to:"restricted_list#index"get"*other-path",to:"other_restricted_list#index"endend
You can also use alambda
:
Rails.application.routes.drawdoconstraints(lambda{|request|RestrictedList.retrieve_ips.include?(request.remote_ip)})doget"*path",to:"restricted_list#index"get"*other-path",to:"other_restricted_list#index"endend
3.11. Wildcard Segments
A route definition can have a wildcard segment, which is a segment prefixed with a star, such as*other
:
get"photos/*other",to:"photos#unknown"
Wildcard segments allow for something called "route globbing", which is a way to specify that a particular parameter (*other
above) be matched to the remaining part of a route.
So the above route would matchphotos/12
or/photos/long/path/to/12
, settingparams[:other]
to"12"
or"long/path/to/12"
.
Wildcard segments can occur anywhere in a route. For example:
get"books/*section/:title",to:"books#show"
would matchbooks/some/section/last-words-a-memoir
withparams[:section]
equals'some/section'
, andparams[:title]
equals'last-words-a-memoir'
.
Technically, a route can have even more than one wildcard segment. The matcher assigns segments to parameters in the order they occur. For example:
get"*a/foo/*b",to:"test#index"
would matchzoo/woo/foo/bar/baz
withparams[:a]
equals'zoo/woo'
, andparams[:b]
equals'bar/baz'
.
3.12. Format Segments
Given this route definition:
get"*pages",to:"pages#show"
By requesting'/foo/bar.json'
, yourparams[:pages]
will be equal to'foo/bar'
with the request format of JSON inparams[:format]
.
The default behavior withformat
is that if included Rails automatically captures it from the URL and includes it in params[:format], butformat
is not required in a URL.
If you want to match URLs without an explicit format and ignore URLs that include a format extension, you could supplyformat: false
like this:
get"*pages",to:"pages#show",format:false
If you want to make the format segment mandatory, so it cannot be omitted, you can supplyformat: true
like this:
get"*pages",to:"pages#show",format:true
3.13. Redirection
You can redirect any path to any other path by using theredirect
helper in your router:
get"/stories",to:redirect("/articles")
You can also reuse dynamic segments from the match in the path to redirect to:
get"/stories/:name",to:redirect("/articles/%{name}")
You can also provide a block toredirect
, which receives the symbolized path parameters and the request object:
get"/stories/:name",to:redirect{|path_params,req|"/articles/#{path_params[:name].pluralize}"}get"/stories",to:redirect{|path_params,req|"/articles/#{req.subdomain}"}
Please note that default 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. You can use the:status
option to change the response status:
get"/stories/:name",to:redirect("/articles/%{name}",status:302)
In all of these cases, if you don't provide the host (http://www.example.com
), Rails will take those details from the current request.
3.14. Routing to Rack Applications
Instead of specifying:to
as a String like'articles#index'
, which corresponds to theindex
method in theArticlesController
class, you can specify anyRack application as the endpoint for a matcher:
match"/application.js",to:MyRackApp,via: :all
As long asMyRackApp
responds tocall
and returns a[status, headers, body]
, the router won't know the difference between the Rack application and a controller action. This is an appropriate use ofvia: :all
, as you will want to allow your Rack application to handle all verbs.
An interesting tidbit -'articles#index'
expands out toArticlesController.action(:index)
, which returns a valid Rack application.
Since procs/lambdas are objects that respond tocall
, you can implement very simple routes (e.g. for health checks) inline, something like:get '/health', to: ->(env) { [204, {}, ['']] }
If you specify a Rack application as the endpoint for a matcher, remember thatthe route will be unchanged in the receiving application. With the followingroute your Rack application should expect the route to be/admin
:
match"/admin",to:AdminApp,via: :all
If you would prefer to have your Rack application receive requests at the rootpath instead, usemount
:
mountAdminApp,at:"/admin"
3.15. Usingroot
You can specify what Rails should route'/'
to with theroot
method:
rootto:"pages#main"root"pages#main"# shortcut for the above
You typically put theroot
route at the top of the file so that it can be matched first.
Theroot
route primarily handlesGET
requests by default. But it is possible to configure it to handle other verbs (e.g.root "posts#index", via: :post
)
You can also use root inside namespaces and scopes as well:
rootto:"home#index"namespace:admindorootto:"admin#index"end
The above will match/admin
to theindex
action for theAdminController
and match/
toindex
action of theHomeController
.
3.16. Unicode Character Routes
You can specify unicode character routes directly. For example:
get"こんにちは",to:"welcome#index"
3.17. Direct Routes
You can create custom URL helpers by callingdirect
. For example:
direct:homepagedo"https://rubyonrails.org"end# >> homepage_url# => "https://rubyonrails.org"
The return value of the block must be a valid argument for theurl_for
method. So, you can pass a valid string URL, Hash, Array, an Active Model instance, or an Active Model class.
direct:commentabledo|model|[model,anchor:model.dom_id]end
direct:maindo{controller:"pages",action:"index",subdomain:"www"}end# >> main_url# => "http://www.example.com/pages"
3.18. Usingresolve
Theresolve
method allows customizing polymorphic mapping of models. For example:
resource:basketresolve("Basket"){[:basket]}
<%=form_withmodel:@basketdo|form|%><!-- basket form --><%end%>
This will generate the singular URL/basket
instead of the usual/baskets/:id
.
4. Customizing Resourceful Routes
While the default routes and helpers generated byresources
will usually serve you well, you may need to customize them in some way. Rails allows for several different ways to customize the resourceful routes and helpers. This section will detail the available options.
4.1. Specifying a Controller to Use
The:controller
option lets you explicitly specify a controller to use for the resource. For example:
resources:photos,controller:"images"
will recognize incoming paths beginning with/photos
but route to theImages
controller:
HTTP Verb | Path | Controller#Action | Named Route 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) |
For namespaced controllers you can use the directory notation. For example:
resources:user_permissions,controller:"admin/user_permissions"
This will route to theAdmin::UserPermissionsController
instance.
Only the directory notation is supported. Specifying the controller withRuby constant notation (e.g.controller: 'Admin::UserPermissions'
) is not supported.
4.2. Specifying Constraints onid
You can use the:constraints
option to specify a required format on the implicitid
. For example:
resources:photos,constraints:{id:/[A-Z][A-Z][0-9]+/}
This declaration constrains the:id
parameter to match the given regular expression. The router would no longer match/photos/1
to this route. Instead,/photos/RR27
would match.
You can specify a single constraint to apply to a number of routes by using the block form:
constraints(id:/[A-Z][A-Z][0-9]+/)doresources:photosresources:accountsend
You can use the moreadvanced constraints available in non-resourceful routes section in this context as well.
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 exampleid: /[^\/]+/
allows anything except a slash.
4.3. Overriding the Named Route Helpers
The:as
option lets you override the default naming for the route helpers. For example:
resources:photos,as:"images"
This will match/photos
and route the requests toPhotosController
as usual,but use the value of the:as
option to name the helpersimages_path
etc., as shown:
HTTP Verb | Path | Controller#Action | Named Route 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) |
4.4. Renaming thenew
andedit
Path Names
The:path_names
option lets you override the defaultnew
andedit
segment in paths. For example:
resources:photos,path_names:{new:"make",edit:"change"}
This would allow paths such as/photos/make
and/photos/1/change
instead of/photos/new
and/photos/1/edit
.
The route helpers and controller action names aren't changed by this option. The two paths shown would havenew_photo_path
andedit_photo_path
helpers and still route to thenew
andedit
actions.
It is also possible to change this option uniformly for all of your routes by using ascope
block:
scopepath_names:{new:"make"}do# rest of your routesend
4.5. Prefixing the Named Route Helpers with:as
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:
scope"admin"doresources:photos,as:"admin_photos"endresources:photos
This changes the route helpers for/admin/photos
fromphotos_path
,new_photos_path
, etc. toadmin_photos_path
,new_admin_photo_path
, etc.Without the addition ofas: 'admin_photos'
on the scopedresources :photos
,the non-scopedresources :photos
will not have any route helpers.
To prefix a group of route helpers, use:as
withscope
:
scope"admin",as:"admin"doresources:photos,:accountsendresources:photos,:accounts
Just as before, this changes the/admin
scoped resource helpers toadmin_photos_path
andadmin_accounts_path
, and allows the non-scopedresources to usephotos_path
andaccounts_path
.
Thenamespace
scope will automatically add:as
as well as:module
and:path
prefixes.
4.6. Using:as
in Nested Resources
The:as
option can override routing helper names for resources in nested routes as well. For example:
resources:magazinesdoresources:ads,as:"periodical_ads"end
This will create routing helpers such asmagazine_periodical_ads_url
andedit_magazine_periodical_ad_path
instead of the defaultmagazine_ads_url
andedit_magazine_ad_path
.
4.7. Parametric Scopes
You can prefix routes with a named parameter:
scope":account_id",as:"account",constraints:{account_id:/\d+/}doresources:articlesend
This will provide you with paths such as/1/articles/9
and will allow you to reference theaccount_id
part of the path asparams[:account_id]
in controllers, helpers, and views.
It will also generate path and URL helpers prefixed withaccount_
, into which you can pass your objects as expected:
account_article_path(@account,@article)# => /1/article/9url_for([@account,@article])# => /1/article/9form_with(model:[@account,@article])# => <form action="/1/article/9" ...>
The:as
option is also not mandatory, but without it, Rails will raise an error when evaluatingurl_for([@account, @article])
or other helpers that rely onurl_for
, such asform_with
.
4.8. Restricting the Routes Created
By default, usingresources
creates routes for the seven default actions (index
,show
,new
,create
,edit
,update
, anddestroy
). You can use the:only
and:except
options to limit which routes are created.
The:only
option tells Rails to create only the specified routes:
resources:photos,only:[:index,:show]
Now, aGET
request to/photos
or/photos/:id
would succeed, but aPOST
request to/photos
will fail to match.
The:except
option specifies a route or list of routes that Rails shouldnot create:
resources:photos,except: :destroy
In this case, Rails will create all of the normal routes except the route fordestroy
(aDELETE
request to/photos/:id
).
If your application has many RESTful routes, using:only
and:except
togenerate only the routes that you actually need can cut down on memory use andspeed up the routing process by eliminatingunusedroutes.
4.9. Translated Paths
Usingscope
, we can alter path names generated byresources
:
scope(path_names:{new:"neu",edit:"bearbeiten"})doresources:categories,path:"kategorien"end
Rails now creates routes to theCategoriesController
.
HTTP Verb | Path | Controller#Action | Named Route 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) |
4.10. Specifying the Singular Form of a Resource
If you need to override the singular form of a resource, you can add a rule to Active Support Inflector viainflections
:
ActiveSupport::Inflector.inflectionsdo|inflect|inflect.irregular"tooth","teeth"end
4.11. Renaming Default Route Parameterid
It is possible to rename the default parameter nameid
with the:param
option. For example:
resources:videos,param: :identifier
Will now useparams[:identifier]
instead ofparams[:id]
.
videos GET /videos(.:format) videos#index POST /videos(.:format) videos#create new_video GET /videos/new(.:format) videos#newedit_video GET /videos/:identifier/edit(.:format) videos#edit
Video.find_by(id:params[:identifier])# Instead ofVideo.find_by(id:params[:id])
You can overrideActiveRecord::Base#to_param
of the associated model to construct a URL:
classVideo<ApplicationRecorddefto_paramidentifierendend
irb>video=Video.find_by(identifier:"Roman-Holiday")irb>edit_video_path(video)=>"/videos/Roman-Holiday/edit"
5. Inspecting Routes
Rails offers a few different ways of inspecting and testing your routes.
5.1. Listing Existing Routes
To get a complete list of routes available in an application, visithttp://localhost:3000/rails/info/routes
in thedevelopment environment. You can also execute thebin/rails routes
command in your terminal to get the same output.
Both methods will list all of your routes, in the same order that they appear inconfig/routes.rb
. For each route, you'll see:
- The route name (if any)
- The HTTP verb used (if the route doesn't respond to all verbs)
- The URL pattern to match
- The routing parameters for the route
For example, here's a small section of thebin/rails routes
output for a RESTful route:
users GET /users(.:format) users#index POST /users(.:format) users#create new_user GET /users/new(.:format) users#newedit_user GET /users/:id/edit(.:format) users#edit
The route name (new_user
above, for example) can be considered the base for deriving route helpers. To get the name of a route helper, add the suffix_path
or_url
to the route name (new_user_path
, for example).
You can also use the--expanded
option to turn on the expanded table formatting mode.
$bin/railsroutes--expanded--[ Route 1 ]----------------------------------------------------Prefix | usersVerb | GETURI | /users(.:format)Controller#Action |users#index--[ Route 2 ]----------------------------------------------------Prefix |Verb | POSTURI | /users(.:format)Controller#Action |users#create--[ Route 3 ]----------------------------------------------------Prefix | new_userVerb | GETURI | /users/new(.:format)Controller#Action |users#new--[ Route 4 ]----------------------------------------------------Prefix | edit_userVerb | GETURI | /users/:id/edit(.:format)Controller#Action |users#edit
5.2. Searching Routes
You can search through your routes with the grep option:-g
. This outputs any routes that partially match the URL helper method name, the HTTP verb, or the URL path.
$bin/railsroutes-g new_comment$bin/railsroutes-g POST$bin/railsroutes-g admin
If you only want to see the routes that map to a specific controller, there's the controller option:-c
.
$bin/railsroutes-cusers$bin/railsroutes-c admin/users$bin/railsroutes-c Comments$bin/railsroutes-c Articles::CommentsController
The output frombin/rails routes
is easier to read if you widen your terminal window until the output lines don't wrap or use the--expanded
option.
5.3. Listing Unused Routes
You can scan your application for unused routes with the--unused
option. An "unused" route in Rails is a route that is defined in the config/routes.rb file but is not referenced by any controller action or view in your application. For example:
$bin/railsroutes--unusedFound 8 unused routes: Prefix Verb URI Pattern Controller#Action people GET /people(.:format) people#index POST /people(.:format) people#create new_person GET /people/new(.:format) people#newedit_person GET /people/:id/edit(.:format) people#edit person GET /people/:id(.:format) people#show PATCH /people/:id(.:format) people#update PUT /people/:id(.:format) people#update DELETE /people/:id(.:format) people#destroy
5.4. Routes in Rails Console
You can access route helpers usingRails.application.routes.url_helpers
within theRails Console. They are also available via theapp object. For example:
irb>Rails.application.routes.url_helpers.users_path=>"/users"irb>user=User.first=>#<User:0x00007fc1eab81628irb>app.edit_user_path(user)=>"/users/1/edit"
6. Testing Routes
Rails offers three built-in assertions designed to make testing routes simpler:
6.1. Theassert_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. For example:
assert_generates"/photos/1",{controller:"photos",action:"show",id:"1"}assert_generates"/about",controller:"pages",action:"about"
6.2. Theassert_recognizes
Assertion
assert_recognizes
is the inverse ofassert_generates
. It asserts that a given path is recognized and routes it to a particular spot in your application. For example:
assert_recognizes({controller:"photos",action:"show",id:"1"},"/photos/1")
You can supply a:method
argument to specify the HTTP verb:
assert_recognizes({controller:"photos",action:"create"},{path:"photos",method: :post})
6.3. Theassert_routing
Assertion
Theassert_routing
assertion checks the route both ways. It combines the functionality of bothassert_generates
andassert_recognizes
. It tests that the path generates the options, and that the options generate the path:
assert_routing({path:"photos",method: :post},{controller:"photos",action:"create"})
7. Breaking Up a Large Route File Withdraw
In a large application with thousands of routes, a singleconfig/routes.rb
file can become cumbersome and hard to read. Rails offers a way to break up a singleroutes.rb
file into multiple small ones using thedraw
macro.
For example, you could add anadmin.rb
file that contains all the routes related to the admin area, anotherapi.rb
file for API related resources, etc.
# config/routes.rbRails.application.routes.drawdoget"foo",to:"foo#bar"draw(:admin)# Will load another route file located in `config/routes/admin.rb`end
# config/routes/admin.rbnamespace:admindoresources:commentsend
Callingdraw(:admin)
inside theRails.application.routes.draw
block itselfwill try to load a route file that has the same name as the argument given(admin.rb
in this example). The file needs to be located inside theconfig/routes
directory or any sub-directory (i.e.config/routes/admin.rb
orconfig/routes/external/admin.rb
).
You can use the normal routing DSL inside a secondary routing file such asadmin.rb
, butdo not surround it with theRails.application.routes.draw
block. That should be used in the mainconfig/routes.rb
file only.
Don't use this feature unless you really need it. Having multiple routing files make it harder to discover routes in one place. For most applications - even those with a few hundred routes - it's easier for developers to have a single routing file. The Rails routing DSL already offers a way to break routes in an organized manner withnamespace
andscope
.