Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Routing Fundamentals  ›  Lesson

RESTful Routes with resources

RESTful Routes 15 minOne resources line maps the seven standard actions (index, show, new, create, edit, update, destroy) to HTTP methods and paths for a collection of things.

RESTful Routes with resources

Every URL your app answers must be declared in config/routes.rb. You could write each one by hand, but most things in an app — books, reviews, members — need the same set of operations: list them, show one, create, change and delete. Rails calls that set a resource and declares it in one line.

The rule

One resources line: seven actions, method plus path.

# config/routes.rb
Rails.application.routes.draw do
  resources :books
end

That line produces:

Method Path Action Purpose
GET /books index list all books
GET /books/new new show the "new book" form
POST /books create save a new book
GET /books/:id show show one book
GET /books/:id/edit edit show the edit form
PATCH/PUT /books/:id update save changes
DELETE /books/:id destroy delete it

:id is a dynamic segment: in /books/7 the controller reads it as params[:id], which is the string "7". This style — nouns in the path, the HTTP method as the verb — is called REST.

Notice that the same path can mean different actions. /books/7 is show with GET, update with PATCH and destroy with DELETE. The method decides.

Need fewer? Trim the list: resources :books, only: [:index, :show] or resources :books, except: [:destroy].

The shortcut

Read a route as "which verb, which noun, one or many?" Many books with no id → index or create. One book with an id → show, update or destroy. A trailing new or edit → a form page.

Decoding PATCH /books/7Step 1 of 4
  1. Verb

    PATCH means "change something that exists".

The trap is expecting GET /books/7/delete. Deleting uses the DELETE method on the plain /books/7 path; in views, button_to with method: :delete sends it.

Drills

Answer fast — trust the rule.

quick drill

Which action handles POST /books?

quick drill

Which request reaches the edit action for book 3?

quick drill

How many actions does a plain resources :books declare?

quick drill

Bookclub's books should only be listed and viewed, never changed through the site. Which line fits?

quick drill

In DELETE /books/12, what value does params[:id] hold?

Remember

  • One resources line: seven actions, each a method plus a path.
  • Shortcut: verb, noun, one or many.
  • Trap: the same path serves several actions; the HTTP method decides which.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainSeven routes from one line

Explain what resources :books gives Bookclub. For the actions show, create and destroy, give the HTTP method and path, and explain why new and edit exist separately from create and update.