Skip to the workspace
Pebellslearn by building
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.

ruby on rails / RESTful Routes with resources

Explore each scene at your own pace.

01 · The rule

The rule

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

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.