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