0
0
Ruby on Railsframework~5 mins

Member and collection routes in Ruby on Rails

Choose your learning style9 modes available
Introduction

Member and collection routes help organize how web addresses connect to actions in your app. They make it easy to handle actions for one item or for many items.

When you want to add a special action for a single item, like 'approve' a specific post.
When you want to add an action that applies to all items, like 'search' all posts.
When you want clear and simple URLs for actions related to one or many records.
When you want to keep your routes organized and easy to understand.
Syntax
Ruby on Rails
resources :items do
  member do
    get 'action_for_one'
  end
  collection do
    get 'action_for_all'
  end
end

member routes add actions that need an item ID in the URL.

collection routes add actions that do not need an item ID.

Examples
This adds a route like /books/:id/preview for previewing one book.
Ruby on Rails
resources :books do
  member do
    get 'preview'
  end
end
This adds a route like /books/search for searching all books.
Ruby on Rails
resources :books do
  collection do
    get 'search'
  end
end
This adds /orders/:id/cancel to cancel one order and /orders/recent to see recent orders.
Ruby on Rails
resources :orders do
  member do
    post 'cancel'
  end
  collection do
    get 'recent'
  end
end
Sample Program

This sets up routes for articles. You can highlight one article or view the archive of all articles.

Ruby on Rails
Rails.application.routes.draw do
  resources :articles do
    member do
      get 'highlight'
    end
    collection do
      get 'archive'
    end
  end
end
OutputSuccess
Important Notes

Member routes always include the item ID in the URL.

Collection routes never include an item ID.

Use member for actions on one record, collection for actions on many.

Summary

Member routes are for actions on a single item and include the item ID in the URL.

Collection routes are for actions on the whole group and do not include an item ID.

They help keep your app's URLs clear and organized.