Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 37 ยท Routing and Controllers

Resourceful Routes

Learn Rails resourceful routing: what resources generates, the seven RESTful actions, singular resources, nested routes, member and collection routes, namespaces and concerns, with a runnable expander.

Most web apps do the same handful of things with each kind of data: list it, show one item, show a form for a new one, create it, show an edit form, update it and delete it. Writing seven routes by hand for every model would be tedious, so Rails gives you one line: resources :articles. This is resourceful routing, and it follows the REST convention.

In this lesson you will see exactly what resources creates, learn the seven standard actions, and then customize it with only, except, nesting, member and collection routes, namespaces and singular resources. The runnable part is a stand-in that expands a resources declaration into its seven routes, so you can see the table that bin/rails routes would print.

What resources :articles creates

Ruby
# config/routes.rb  (read-only)
Rails.application.routes.draw do
  resources :articles
end

That one line gives you seven routes:

Verb Path Action Purpose Helper
GET /articles index List all articles articles_path
GET /articles/new new Form for a new article new_article_path
POST /articles create Save the new article articles_path
GET /articles/:id show Show one article article_path(id)
GET /articles/:id/edit edit Form to edit edit_article_path(id)
PATCH/PUT /articles/:id update Save the changes article_path(id)
DELETE /articles/:id destroy Delete it article_path(id)

Notice that several routes share the same path and differ only by verb. That is the heart of REST: the URL names the thing, the verb names the action. GET /articles/5 reads article 5, DELETE /articles/5 removes it.

flowchart LR
  I["index<br/>GET /articles"] --> S["show<br/>GET /articles/1"]
  N["new<br/>GET /articles/new"] -->|"submit form"| C["create<br/>POST /articles"]
  S --> E["edit<br/>GET /articles/1/edit"]
  E -->|"submit form"| U["update<br/>PATCH /articles/1"]
  S --> D["destroy<br/>DELETE /articles/1"]

The seven actions: new and edit show forms, create and update receive them.

Other standard names such as articles_url (full URL) exist too. The controller for this resource is ArticlesController, with methods named after the actions.

Stand-in: expanding resources

This stand-in does what the router does: take a resource name and produce the seven routes with their helper names. It uses a Struct and simple pluralization.

Ruby Stand-in: what `resources` expands into

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Limiting actions with only and except

Do not expose actions you do not use. A read-only catalogue needs just two:

Ruby
# read-only
resources :products, only: [:index, :show]
resources :sessions, only: [:new, :create, :destroy]
resources :posts, except: [:destroy]

Unused routes are extra surface area for attackers and extra noise in bin/rails routes.

Singular resources

When there is only one of something for each user, such as a profile or a shopping cart, use the singular resource. It has no :id and no index, and the controller name is still plural:

Ruby
# read-only
resource :profile
# GET /profile, GET /profile/new, POST /profile, GET /profile/edit,
# PATCH /profile, DELETE /profile  -> ProfilesController

Nested resources

Comments belong to an article, so the URL can show that:

Ruby
# read-only
resources :articles do
  resources :comments
end
# GET  /articles/5/comments       -> comments#index   (params[:article_id] == "5")
# POST /articles/5/comments       -> comments#create
# GET  /articles/5/comments/9     -> comments#show    (params[:id] == "9")
# helper: article_comments_path(5), article_comment_path(5, 9)

The parent id arrives as params[:article_id]. A good rule is to nest one level only. Deeper nesting such as /a/1/b/2/c/3 is awkward; use shallow: true or give child records their own top-level route once you have the id:

Ruby
# read-only
resources :articles do
  resources :comments, shallow: true
end
# index/new/create stay nested; show/edit/update/destroy use /comments/:id

Member and collection routes

Sometimes you need an action that is not one of the seven. A member route works on one record (it has an :id), a collection route works on the whole set.

Ruby
# read-only
resources :articles do
  member do
    post :publish         # POST /articles/5/publish   -> articles#publish
  end
  collection do
    get :search           # GET  /articles/search      -> articles#search
  end
end

Pause before adding a custom action. Often a better design is a new resource: instead of post :publish on articles, create resources :publications, only: :create nested under articles. The controller stays small and uses the seven standard actions.

Namespaces, scopes and concerns

A namespace adds a URL prefix and a module for the controller. It is how you build an admin area or API versions:

Ruby
# read-only
namespace :admin do
  resources :articles       # /admin/articles -> Admin::ArticlesController
end

namespace :api do
  namespace :v1 do
    resources :articles, only: [:index, :show]   # Api::V1::ArticlesController
  end
end

scope changes only the URL (scope "/blog" { resources :articles } gives /blog/articles), and scope module: "admin" changes only the controller module. For reusable groups of routes, a concern captures them once:

Ruby
# read-only
concern :commentable do
  resources :comments
end

resources :articles, concerns: :commentable
resources :photos,   concerns: :commentable

The folder layout for a namespace follows Zeitwerk naming: app/controllers/admin/articles_controller.rb.

Stand-in: nested routes with a parent id

Here is the nested expansion, so you can see how article_id appears.

Ruby Stand-in: nested resource routes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Always scope child lookups through the parent: @article.comments.find(params[:id]), not Comment.find(params[:id]). Otherwise a visitor can read comments of articles they should not see by changing the number in the URL.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many routes does resources :articles create (counting PATCH and PUT as one)?

    index, new, create, show, edit, update and destroy: seven routes.
  2. 2. Which two actions show forms rather than change data?

    new shows the empty form, edit shows the filled-in form; create and update receive them.
  3. 3. In resources :articles do resources :comments end, how does the controller learn the article?

    The nested route adds :article_id, and the comment's own id is :id.
  4. 4. What is the difference between a member and a collection route?

    /articles/5/publish is a member route; /articles/search is a collection route.

Summary

  • resources :things creates seven RESTful routes: index, new, create, show, edit, update, destroy.
  • The URL names the thing and the HTTP verb names the action.
  • Use only/except to expose only what you need, and resource (singular) for one-per-user things.
  • Nest one level; use shallow: true or top-level routes beyond that. Scope lookups through the parent.
  • member/collection add custom actions, namespace builds admin or API areas, concern shares route groups.

Next: Controllers and Actions