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
endThat 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.
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.
Which action handles POST /books?
Which request reaches the edit action for book 3?
How many actions does a plain resources :books declare?
Bookclub's books should only be listed and viewed, never changed through the site. Which line fits?
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.
