How to Use Member and Collection Routes in Ruby on Rails
In Ruby on Rails, use
member routes to add custom actions that operate on a single resource item, and collection routes for actions that apply to the entire resource collection. Define them inside the resources block in config/routes.rb to create RESTful custom routes easily.Syntax
Inside the resources block, use member to define routes that require an ID (operate on one item), and collection for routes that don't need an ID (operate on all items).
member do: Defines routes like/resources/:id/action.collection do: Defines routes like/resources/action.- Inside these blocks, use HTTP verbs like
get,post, etc., to specify the action.
ruby
resources :photos do
member do
get 'preview'
end
collection do
get 'search'
end
endExample
This example shows how to add a preview action for a single photo and a search action for all photos.
ruby
Rails.application.routes.draw do
resources :photos do
member do
get 'preview'
end
collection do
get 'search'
end
end
end
# Controller: app/controllers/photos_controller.rb
class PhotosController < ApplicationController
def preview
@photo = Photo.find(params[:id])
render plain: "Previewing photo ##{@photo.id}"
end
def search
render plain: "Searching all photos"
end
endOutput
GET /photos/1/preview => "Previewing photo #1"
GET /photos/search => "Searching all photos"
Common Pitfalls
- Defining a
memberroute but forgetting it needs an:idparameter causes routing errors. - Using
collectionwhen the action requires an ID will fail because no ID is passed. - Not specifying the HTTP verb inside
memberorcollectionblocks leads to unexpected routes.
ruby
resources :photos do # Wrong: 'preview' needs an ID, so it must be a member route collection do get 'preview' end # Right: member do get 'preview' end end
Quick Reference
| Route Type | URL Pattern | Purpose | Example |
|---|---|---|---|
| member | /photos/:id/action | Action on a single resource | GET /photos/1/preview |
| collection | /photos/action | Action on the whole collection | GET /photos/search |
Key Takeaways
Use
member routes for actions on individual resource items requiring an ID.Use
collection routes for actions on the entire resource collection without an ID.Define these routes inside the
resources block in config/routes.rb.Always specify the HTTP verb (get, post, etc.) inside
member or collection blocks.Avoid mixing
member and collection incorrectly to prevent routing errors.