difference between collection route and member route in ruby on rails?

Ruby on-RailsRuby

Ruby on-Rails Problem Overview


What is the difference between collection routes and member routes in Rails?

For example,

resources :photos do
  member do
    get :preview
  end
end

versus

resources :photos do
  collection do
    get :search
  end
end

I don't understand.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

A member route will require an ID, because it acts on a member. A collection route doesn't because it acts on a collection of objects. Preview is an example of a member route, because it acts on (and displays) a single object. Search is an example of a collection route, because it acts on (and displays) a collection of objects.

Solution 2 - Ruby on-Rails

			    URL					Helper						Description
----------------------------------------------------------------------------------------------------------------------------------
member			/photos/1/preview 	preview_photo_path(photo)	Acts on a specific resource so required id (preview specific photo)
collection		/photos/search		search_photos_path			Acts on collection of resources(display all photos)

Solution 3 - Ruby on-Rails

Theo's answer is correct. For documentation's sake, I'd like to also note that the two will generate different path helpers.

member {get 'preview'} will generate:

preview_photo_path(@photo) # /photos/1/preview

collection {get 'search'} will generate:

search_photos_path # /photos/search

Note plurality!

Solution 4 - Ruby on-Rails

  1. :collection - Add named routes for other actions that operate on the collection. Takes a hash of #{action} => #{method}, where method is :get/:post/:put/:delete, an array of any of the previous, or :any if the method does not matter. These routes map to a URL like /users/customers_list, with a route of customers_list_users_url.

> map.resources :users, :collection => { :customers_list=> :get }

  1. :member - Same as :collection, but for actions that operate on a specific member.

> map.resources :users, :member => { :inactive=> :post }

it treated as /users/1;inactive=> [:action => 'inactive', :id => 1]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionnever_had_a_nameView Question on Stackoverflow
Solution 1 - Ruby on-RailsTheoView Answer on Stackoverflow
Solution 2 - Ruby on-RailsAmit PatelView Answer on Stackoverflow
Solution 3 - Ruby on-Railstybro0103View Answer on Stackoverflow
Solution 4 - Ruby on-RailsBeena ShettyView Answer on Stackoverflow