0
0
Ruby on Railsframework~3 mins

Why Member and collection routes in Ruby on Rails? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to make your app's special actions neat and easy with member and collection routes!

The Scenario

Imagine you have a website with many items, like books. You want to add special actions: one that works on a single book (like marking it as favorite) and another that works on all books (like showing all favorites). Doing this by hand means writing many separate URLs and code for each case.

The Problem

Manually creating URLs for each item and for the whole collection is slow and confusing. You might mix up URLs or forget to handle some cases. It's easy to make mistakes and hard to keep track of all routes as your app grows.

The Solution

Member and collection routes let you cleanly define actions for one item or for the whole group inside your routes file. Rails automatically creates the right URLs and helpers, so you write less code and avoid errors.

Before vs After
Before
get '/books/:id/favorite' => 'books#favorite'
get '/books/favorites' => 'books#favorites'
After
resources :books do
  member do
    get 'favorite'
  end
  collection do
    get 'favorites'
  end
end
What It Enables

You can easily add custom actions for single items or entire collections with clear, maintainable routes and helpers.

Real Life Example

On a photo gallery site, you might want to add a 'like' button for each photo (member route) and a page showing all liked photos (collection route). Member and collection routes make this simple and organized.

Key Takeaways

Manual URL handling is error-prone and hard to maintain.

Member routes handle actions on single items.

Collection routes handle actions on groups of items.