Veja mais em rubyonrails.org: Mais Ruby on Rails

Rotas do Rails de Fora pra Dentro

Esse guia cobre os recursos de roteamento que os usuários podem utilizar no Rails.

Após ler esse guia, você saberá:

1 O Propósito do Roteador do Rails

O roteador do Rails organiza URLs e as direcionam para uma ação de um controller ou de um aplicativo Rack. Também pode gerar caminhos e URLs, evitando a necessidade de codificar sequências de caracteres em suas visualizações.

1.1 Conectando URLs ao código

Quando sua aplicação Rails recebe uma requisição para:

GET /patients/17

ela solicita ao roteador que corresponda com uma ação do controller. Se a primeira rota correspondente for:

get '/patients/:id', to: 'patients#show'

a requisição é direcionada para o controller patients na ação show com { id: '17' } em params.

O Rails usa snake_case para nomes de controller no roteamento, se você tem um controller com várias palavras como MonsterTrucksController, você deve usar monster_trucks#show, por exemplo.

1.2 Gerando Caminhos e URLs a partir do código

Você também pode gerar caminhos e URLs. Se a rota acima for modificada para ser:

get '/patients/:id', to: 'patients#show', as: 'patient'

e sua aplicação contém esse código no controller:

@patient = Patient.find(params[:id])

e isso na view correspondente:

<%= link_to 'Patient Record', patient_path(@patient) %>

então seu roteador irá gerar o caminho /patients/17. Isso reduz a fragilidade da sua view e faz seu código mais simples de entender. Observe que o id não não precisa ser especificado no helper da rota.

1.3 Configurando o Roteador do Rails

As rotas para sua aplicação ou engine estão dentro do arquivo config/routes.rb e tipicamente se parecem com isso:

Rails.application.routes.draw do
  resources :brands, only: [:index, :show] do
    resources :products, only: [:index, :show]
  end

  resource :basket, only: [:show, :update, :destroy]

  resolve("Basket") { route_for(:basket) }
end

Como isso é um arquivo padrão do Ruby você pode utilizar de todos os seus recursos para te ajudar a definir suas rotas, porém tenha cautela com nomes de variáveis já que ela pode conflitar com os métodos da DSL do roteador.

O bloco Rails.application.routes.draw do ... end que encapsula suas definições de rotas é necessário para estabelecer o escopo do roteador da DSL e não deve ser deletado.

2 Resource Routing: the Rails Default

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

2.1 Resources on the Web

Browsers request pages from Rails by making a request for a URL using a specific HTTP method, such as GET, POST, 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:

DELETE /photos/17

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

resources :photos

Rails would dispatch that request to the destroy action on the photos controller with { id: '17' } in params.

2.2 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 a specific CRUD operation in a database. A single entry in the routing file, such as:

resources :photos

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

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

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

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.

2.3 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:

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

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.

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 to resources:

resources :photos, :books, :videos

This works exactly the same as:

resources :photos
resources :books
resources :videos

2.5 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:

get 'profile', to: 'users#show'

Passing a String to to: will expect a controller#action format. When using a Symbol, the to: option should be replaced with action:. When using a String without a #, the to: option should be replaced with controller::

get 'profile', action: :show, controller: 'users'

This resourceful route:

resource :geocoder
resolve('Geocoder') { [:geocoder] }

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

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

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:

  • 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

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

namespace :admin do
  resources :articles, :comments
end

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

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)

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

scope module: 'admin' do
  resources :articles, :comments
end

or, for a single case:

resources :articles, module: 'admin'

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

scope '/admin' do
  resources :articles, :comments
end

or, for a single case:

resources :articles, path: '/admin/articles'

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 ArticlesController:

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 a namespace 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:

class Magazine < ApplicationRecord
  has_many :ads
end

class Ad < ApplicationRecord
  belongs_to :magazine
end

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

resources :magazines do
  resources :ads
end

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

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)).

2.7.1 Limits to Nesting

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

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

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

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

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

Resources should never be nested more than 1 level deep.

2.7.2 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:

resources :articles 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:

resources :articles 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:

resources :articles, 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:

shallow do
  resources :articles do
    resources :comments
    resources :quotes
    resources :drafts
  end
end

There exist two options for scope to customize shallow routes. :shallow_path prefixes member paths with the specified parameter:

scope shallow_path: "sekret" do
  resources :articles 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 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 named route helpers:

scope shallow_prefix: "sekret" do
  resources :articles 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 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 and routes. To define a concern:

concern :commentable do
  resources :comments
end

concern :image_attachable do
  resources :images, only: :index
end

These concerns can be used in resources to avoid code duplication and share behavior across routes:

resources :messages, concerns: :commentable

resources :articles, concerns: [:commentable, :image_attachable]

The above is equivalent to:

resources :messages do
  resources :comments
end

resources :articles 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:

namespace :articles do
  concerns :commentable
end

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 :magazines do
  resources :ads
end

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

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

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

<%= link_to 'Ad details', url_for([@magazine, @ad]) %>

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

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

If you wanted to link to just a magazine:

<%= link_to 'Magazine details', @magazine %>

For other actions, you just need to insert the action name as the first element of the array:

<%= 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.

2.10 Adding More RESTful Actions

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

2.10.1 Adding Member Routes

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

resources :photos do
  member do
    get 'preview'
  end
end

This will recognize /photos/1/preview with GET, and route to the preview action of PhotosController, 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 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:

resources :photos do
  get 'preview', on: :member
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]. Route helpers will also be renamed from preview_photo_url and preview_photo_path to photo_preview_url and photo_preview_path.

2.10.2 Adding Collection Routes

To add a route to the collection:

resources :photos do
  collection do
    get 'search'
  end
end

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

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

resources :photos do
  get 'search', on: :collection
end

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 :comments do
  get 'preview', on: :new
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.

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.

3 Non-Resourceful Routes

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

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

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

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 incoming request of /photos/1 is processed by this route (because it hasn't matched any previous route in the file), then the result will be to invoke the display action of the PhotosController, and to make the final parameter "1" available as params[:id]. This route will also route the incoming request of /photos to PhotosController#display, since :id is an optional parameter, denoted by parentheses.

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 of params. If you set up this route:

get 'photos/:id/:user_id', to: 'photos#show'

An incoming path of /photos/1/2 will be dispatched to the show action of the PhotosController. params[:id] will be "1", and params[:user_id] will be "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 fragment:

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

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

get 'photos/:id', to: 'photos#show'

An incoming path of /photos/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' }.

3.5 Defining Defaults

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 match photos/12 to the show action of PhotosController, and set params[:format] to "jpg".

You can also use defaults in a block format to define the defaults for multiple items:

defaults format: :json do
  resources :photos
end

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 for any route using the :as option:

get 'exit', to: 'sessions#destroy', as: :logout

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

You can also use this to override routing methods defined by resources, like this:

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.

3.7 HTTP Verb Constraints

In general, you should use the get, post, put, patch 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:

match 'photos', to: 'photos#show', via: [:get, :post]

You can match all verbs to a particular route using via: :all:

match 'photos', to: 'photos#show', via: :all

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.

GET in Rails won't check for CSRF token. You should never write to the database from GET requests, for more information see the security guide on CSRF countermeasures.

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}/ }

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}/

:constraints takes regular expressions 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.

For example, the following routes would allow for articles 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:

get '/:id', to: 'articles#show', constraints: { id: /\d.+/ }
get '/:username', to: 'users#show'

3.9 Request-Based Constraints

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

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

get 'photos', to: 'photos#index', constraints: { subdomain: 'admin' }

You can also specify constraints in a block form:

namespace :admin do
  constraints subdomain: 'admin' do
    resources :photos
  end
end

Request constraints work by calling a method on the Request object with the same name as the hash key and then compare the return value with the hash value. Therefore, constraint values should match the corresponding Request object method return type. For example: constraints: { subdomain: 'api' } will match an api subdomain as expected, however using a symbol constraints: { subdomain: :api } will not, because request.subdomain returns 'api' as a String.

There is an exception for the format 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 the format constraint is only applied as such when enforced through a hash. For example, get 'foo', constraints: { format: 'json' } will match GET /foo because the format is optional by default. However, you can use a lambda like in get 'foo', constraints: lambda { |req| req.format == :json } and the route will only match explicit JSON requests.

3.10 Advanced Constraints

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

class RestrictedListConstraint
  def initialize
    @ips = RestrictedList.retrieve_ips
  end

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

Rails.application.routes.draw do
  get '*path', to: 'restricted_list#index',
    constraints: RestrictedListConstraint.new
end

You can also specify constraints as a lambda:

Rails.application.routes.draw do
  get '*path', to: 'restricted_list#index',
    constraints: lambda { |request| RestrictedList.retrieve_ips.include?(request.remote_ip) }
end

Both the matches? method and the lambda gets the request object as an argument.

3.11 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:

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". The fragments prefixed with a star are called "wildcard segments".

Wildcard segments can occur anywhere in a route. For example:

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'.

Technically, a route can have even more than one wildcard segment. The matcher assigns segments to parameters in an intuitive way. For example:

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'.

By requesting '/foo/bar.json', your params[:pages] will be equal 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:

get '*pages', to: 'pages#show', format: false

If you want to make the format segment mandatory, so it cannot be omitted, you can supply format: true like this:

get '*pages', to: 'pages#show', format: true

3.12 Redirection

You can redirect any path to another path using the redirect 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 to redirect, 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 leading host (http://www.example.com), Rails will take those details from the current request.

3.13 Routing to Rack Applications

Instead of a String like 'articles#index', which corresponds to the index action in the ArticlesController, you can specify any Rack application as the endpoint for a matcher:

match '/application.js', to: MyRackApp, via: :all

As long as MyRackApp 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.

For the curious, 'articles#index' actually expands out to ArticlesController.action(:index), which returns a valid Rack application.

If you specify a Rack application as the endpoint for a matcher, remember that the route will be unchanged in the receiving application. With the following route 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 root path instead, use mount:

mount AdminApp, at: '/admin'

3.14 Using root

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

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.

The root route only routes GET requests to the action.

You can also use root inside namespaces and scopes as well. For example:

namespace :admin do
  root to: "admin#index"
end

root to: "home#index"

3.15 Unicode character routes

You can specify unicode character routes directly. For example:

get 'こんにちは', to: 'welcome#index'

3.16 Direct routes

You can create custom URL helpers directly. For example:

direct :homepage do
  "http://www.rubyonrails.org"
end

# >> homepage_url
# => "http://www.rubyonrails.org"

The return value of the block must be a valid argument for the url_for method. So, you can pass a valid string URL, Hash, Array, an Active Model instance, or an Active Model class.

direct :commentable do |model|
  [ model, anchor: model.dom_id ]
end

direct :main do
  { controller: 'pages', action: 'index', subdomain: 'www' }
end

3.17 Using resolve

The resolve method allows customizing polymorphic mapping of models. For example:

resource :basket

resolve("Basket") { [:basket] }

<%= form_for @basket do |form| %>
  <!-- basket form -->
<% end %>

This will generate the singular URL /basket instead of the usual /baskets/:id.

4 Customizando Rotas com Recursos

Enquanto as rotas padrão e helpers gerados por resources :articles normalmente atendem a maior parte dos casos de uso, você pode querer customizá-los de alguma forma. O Rails lhe permite customizar virtualmente qualquer parte genérica dos helpers de recursos.

4.1 Especificando um Controller para Usar

A opção :controller permite que você especifique um controller de forma explícita para usar para o recurso. Por exemplo:

resources :photos, controller: 'images'

vai reconhecer caminhos requisitados iniciando com /photos mas vai rotear para o controller Images:

Verbo HTTP Caminho Controller#Action Nome do Helper de Rota
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)

Utilize photos_path, new_photo_path, etc. para gerar caminhos para este recurso.

Você pode usar a notação de diretório para controllers com namespaces associados. Por exemplo:

resources :user_permissions, controller: 'admin/user_permissions'

Isso vai direcionar a chamada da rota para o controller Admin::UserPermissions.

Apenas a notação de diretório é suportada. Especificar o controller com a notação de constante do Ruby (e.g. controller: 'Admin::UserPermissions') pode causar problemas e resulta em um aviso.

4.2 Especificando Restrições

Você pode usar a opção :constraints pra especificar um formato exigido no id implícito. Por exemplo:

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

Essa declaração restringe o parâmetro :id de forma que ele seja igual à especificação da expressão regular. Então, nesse caso, o roteador não iria mais aceitar /photos/1 para essa rota. Por outro lado, a requisição /photos/RR27 seria aceita.

Você pode especificar uma única restrição para aplicar a mais de uma rota usando a forma de bloco:

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

De fato, você pode usar restrições mais avançadas disponíveis em rotas sem recursos nesse contexto.

Por padrão o parâmetro :id não aceita pontos - isto acontece pois os pontos são usados como separadores para rotas com formato de arquivo especificado. Se você precisa usar um ponto dentro do :id adicione uma restrição que sobrescreva isto - a expressão regular id: /[^\/]+/ permite tudo exceto uma barra (\).

4.3 Sobrescrevendo Helpers de Nome de Rota

A opção :as permite que você sobrescreva a convenção de nomes para os helpers de nome de rota. Por exemplo:

resources :photos, as: 'images'

vai reconhecer chamadas que chegarem iniciando com /photos e direcionar as requisições para o PhotosController, mas vai usar o valor especificado na opção :as para nomear os helpers.

Verbo HTTP Caminho Controller#Action Nome do Helper de Rota
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 Sobrescrevendo os Segmentos new e edit

A opção :path_names permite que você sobrescreva os segmentos new e edit gerados automaticamente nos caminhos:

resources :photos, path_names: { new: 'make', edit: 'change' }

Isso faz o roteamento reconhecer caminhos como:

/photos/make
/photos/1/change

Os nomes das ações não sofrem alterações devido a esta opção. Os dois caminhos exibidos ainda apontarão para as ações new e edit.

Se você quiser mudar esta opção para todas as rotas, você pode usar um scope.

scope path_names: { new: 'make' } do
  # rest of your routes
end

4.5 Prefixando os Helpers de Nome de Rota

Você pode usar a opção :as pra prefixar os helpers de nome de rota que o Rails gera. Use esta opção para evitar colisões de nomes entre rotas usando um escopo de caminho. Por exemplo:

scope 'admin' do
  resources :photos, as: 'admin_photos'
end

resources :photos

Isto fornecerá helpers de rota como admin_photos_path, new_admin_photo_path, etc.

Para prefixar um grupo de helpers de rota, utilize :as com scope:

scope 'admin', as: 'admin' do
  resources :photos, :accounts
end

resources :photos, :accounts

Isto irá gerar rotas como admin_photos_path e admin_accounts_path que são mapeadas para /admin/photos e /admin/accounts respectivamente.

O scope namespace adicionará automaticamente os prefixos :as, assim como :module e :path.

Você pode prefixar as rotas com um named parameter também:

scope ':username' do
  resources :articles
end

Isto vai lhe deixar com URLs como /bob/articles/-1 e também permitirá referir à parte username do caminho como params[:username] nos controllers, helpers, e views.

4.6 Restringindo as Rotas Criadas

O Rails cria rotas para sete ações diferentes (index, show, new, create, edit, update, and destroy) por padrão pra cada rota RESTful na sua aplicação. A opção :only diz ao Rails para criar apenas as rotas especificadas:

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

Agora, a requisição GET para /photos daria certo, mas uma requisição POST para /photos (que por padrão iria para ação create) falhará.

A opção :except específica uma rota ou lista de rotas que o Rails não deve criar:

resources :photos, except: :destroy

Nesse caso, o Rails vai criar todas as rotas normais exceto a rota para destroy (uma requisição DELETE para /photos/:id).

Se sua aplicação tem muitas rotas RESTful, usar :only e :except para gerar somente as rotas que você realmente precisa pode reduzir o consumo de memória e agilizar o processo de roteamento.

4.7 Traduzindo Caminhos

Podemos alterar nomes de caminho gerados por resources usando scope:

scope(path_names: { new: 'neu', edit: 'bearbeiten' }) do
  resources :categories, path: 'kategorien'
end

O Rails agora cria rotas para o CategoriesController.

Verbo HTTP Caminho Controller#Action Nome do Helper de Rota
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.8 Sobrescrevendo a Forma Singular

Se você quer definir a forma singular de um recurso, você deve colocar regras adicionais para o Inflector:

ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular 'tooth', 'teeth'
end

4.9 Usando :as em Recursos Aninhados

A opção :as sobrescreve o nome gerado automaticamente para o recurso em helpers de rota aninhados. Por exemplo:

resources :magazines do
  resources :ads, as: 'periodical_ads'
end

Isto criará helpers de rota como magazine_periodical_ads_url e edit_magazine_periodical_ad_path.

4.10 Sobrescrevendo Parâmetros de Nome de Rota

A opção :param sobrescreve o identificador padrão de recurso :id (nome do segmento dinâmico usado para gerar as rotas). Você pode acessar o segmento do seu controller usando params[<:param>].

resources :videos, param: :identifier

    videos GET  /videos(.:format)                  videos#index
           POST /videos(.:format)                  videos#create
 new_video GET  /videos/new(.:format)              videos#new
edit_video GET  /videos/:identifier/edit(.:format) videos#edit

Video.find_by(identifier: params[:identifier])

Você pode sobrescrever ActiveRecord::Base#to_param de um model relacionado para construir a URL:

class Video < ApplicationRecord
  def to_param
    identifier
  end
end

video = Video.find_by(identifier: "Roman-Holiday")
edit_video_path(video) # => "/videos/Roman-Holiday/edit"

5 Inspecionando e Testando Rotas

Rails oferece recursos para inspecionar e testar suas rotas.

5.1 Listando Rotas Existentes

Para obter uma lista completa de rotas disponíveis na sua aplicação, visite http://localhost:3000/rails/info/routes no browser quando o servidor estiver rodando em ambiente de desenvolvimento. Você pode também executar o comando rails routes no terminal para reproduzir o mesmo resultado.

Ambos os métodos irão listas todas suas rotas, na mesma ordem que aparece em config/routes.rb. Para cada rota, você irá ver:

  • O Nome da rota (se houver)
  • O verbo HTTP usado (se a rota não responder a todos os verbos)
  • O padrão ao qual a URL deve corresponder
  • Os parâmetros para a cada rota

Por exemplo, segue uma pequena parte da resposta rails routes para uma rota RESTful:

    users GET    /users(.:format)          users#index
          POST   /users(.:format)          users#create
 new_user GET    /users/new(.:format)      users#new
edit_user GET    /users/:id/edit(.:format) users#edit

Você pode também utilizar a opção --expanded para ativar o modo de formatação por tabela expandida.

$ rails routes --expanded

--[ Route 1 ]----------------------------------------------------
Prefix            | users
Verb              | GET
URI               | /users(.:format)
Controller#Action | users#index
--[ Route 2 ]----------------------------------------------------
Prefix            |
Verb              | POST
URI               | /users(.:format)
Controller#Action | users#create
--[ Route 3 ]----------------------------------------------------
Prefix            | new_user
Verb              | GET
URI               | /users/new(.:format)
Controller#Action | users#new
--[ Route 4 ]----------------------------------------------------
Prefix            | edit_user
Verb              | GET
URI               | /users/:id/edit(.:format)
Controller#Action | users#edit

Você pode procurar por rotas utilizando a opção grep: -g. Isso resulta qualquer rota que corresponda parcialmente ao nome do método da URL, o verbo HTTP, ou a URL.

$ rails routes -g new_comment
$ rails routes -g POST
$ rails routes -g admin

Se você quiser ver somente as rotas que mapeiam um controller especifico, existe a opção -c.

$ rails routes -c users
$ rails routes -c admin/users
$ rails routes -c Comments
$ rails routes -c Articles::CommentsController

O resultado do comando rails routes fica muito mais legível se você ampliar a janela do seu terminal até que não haja quebra de linha.

5.2 Testando Rotas

Rotas deveriam ser incluidas na sua estratégia de testes (assim como resto da sua aplicação). Rails oferece três validações nativas desenvolvidas para fazer os testes de rotas mais simples:

  • assert_generates
  • assert_recognizes
  • assert_routing
5.2.1 A validação assert_generates

assert_generates valida que um conjunto de opções em particular gera um caminho equivalente que pode ser usar com rota padrão ou rota customizada. Por exemplo:

assert_generates '/photos/1', { controller: 'photos', action: 'show', id: '1' }
assert_generates '/about', controller: 'pages', action: 'about'

5.2.2 A validação assert_recognizes

assert_recognizes é o inverso de assert_generates. Valida que um dado caminho é reconhecido e roteia-o a um lugar determinado na sua aplicação. Por exemplo:

assert_recognizes({ controller: 'photos', action: 'show', id: '1' }, '/photos/1')

Você pode passar um argumento :method para especificar um verbo HTTP:

assert_recognizes({ controller: 'photos', action: 'create' }, { path: 'photos', method: :post })

5.2.3 A validação assert_routing

A validação assert_routing testa a rota dos dois jeitos: Testa que um caminho gera opções, e que opções gera um caminho. Logo, Ela combina as validações assert_generates e assert_recognizes:

assert_routing({ path: 'photos', method: :post }, { controller: 'photos', action: 'create' })

Feedback

Você é incentivado a ajudar a melhorar a qualidade deste guia.

Por favor, contribua se vir qualquer erros, inclusive erros de digitação. Para começar, você pode ler nossa sessão de contribuindo com a documentação.

Você também pode encontrar conteúdo incompleto ou coisas que não estão atualizadas. Por favor, adicione qualquer documentação em falta na master do Rails. Certifique-se de checar o Edge Guides (en-US) primeiro para verificar se o problema já foi resolvido ou não no branch master. Verifique as Diretrizes do Guia Ruby on Rails para estilo e convenções.

Se, por qualquer motivo, você encontrar algo para consertar, mas não conseguir consertá-lo, por favor abra uma issue no nosso Guia.

E por último, mas não menos importante, qualquer tipo de discussão sobre a documentação do Ruby on Rails é muito bem vinda na lista de discussão rubyonrails-docs e nas issues do Guia em português.