Discover how to make your app's special actions neat and easy with member and collection routes!
Why Member and collection routes in Ruby on Rails? - Purpose & Use Cases
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.
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.
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.
get '/books/:id/favorite' => 'books#favorite' get '/books/favorites' => 'books#favorites'
resources :books do
member do
get 'favorite'
end
collection do
get 'favorites'
end
endYou can easily add custom actions for single items or entire collections with clear, maintainable routes and helpers.
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.
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.