Nested Routes and Extra Actions
A review makes no sense without the book it is about, and "borrow this book" is not one of the seven standard actions. Routing handles both: nesting shows the parent-child link in the URL, and member or collection routes add the actions REST does not cover.
The rule
Nest what belongs; member for one, collection for all.
Nesting puts one resource inside another:
resources :books do
resources :reviews
endNow review URLs carry the book: GET /books/7/reviews, POST /books/7/reviews. The parent's id arrives as params[:book_id], and helpers gain the parent's name: book_reviews_path(@book), new_book_review_path(@book). A rule of thumb is to nest only one level deep; /members/2/books/7/reviews/9 is painful to build and read.
For deep links you can use shallow: true: actions that need the collection (index, new, create) stay nested, while show, edit, update and destroy use /reviews/9, since a review's id already identifies it.
Extra actions go in a block:
resources :books do
member do
post :borrow # POST /books/:id/borrow -> borrow_book_path(@book)
end
collection do
get :available # GET /books/available -> available_books_path
end
endA member route has an :id, because it acts on one record. A collection route has none, because it acts on the list. Both are handled by BooksController (borrow and available actions).
The shortcut
Ask two questions. Can the child exist without the parent? No → nest it. Is the new action about one record or the whole set? One → member. All → collection.
One or all?
A member marks one book as read, so it needs the book's id.
The trap is adding a custom action when a resource would do. "Borrowing" could also be resources :loans, with create and destroy. If the extra actions pile up, look for the hidden noun.
Drills
Answer fast — trust the rule.
With reviews nested in books, which param holds the book's id in ReviewsController#create?
Which helper lists the reviews of @book?
A "search books" page should live at /books/search. Which block holds get :search?
What path does member do post :borrow end inside resources :books produce?
Remember
- Nest what belongs, one level deep; member for one, collection for all.
- Shortcut: can it live without the parent? One record or all?
- Trap: piling up custom actions when a new resource is hiding in the verb.
