Skip to the workspace
Pebellslearn by building
Routing Fundamentals  ›  Lesson

Nested Routes and Extra Actions

Nested Routes 15 minNesting puts a child resource under its parent's URL, and member or collection blocks add non-RESTful actions that act on one record or on the whole list.

ruby on rails / Nested Routes and Extra Actions

Explore each scene at your own pace.

01 · The rule

The rule

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
end

Now 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
end

A 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).

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