Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What are collection routes?

Collection Route means a route established by the designated officer, covering an area within which waste will be collected by the city.

What are member routes?

Member routes can be defined for actions that are performed on a member of the resource . Let's take an example. Let's say we have a post resource and we need an ability to archive a post. To define routes to achive the functionality above, we will use member routes as given below.

How many types of routes are there in Rails?

Rails RESTful Design which creates seven routes all mapping to the user controller. Rails also allows you to define multiple resources in one line.

What is the difference between resource and resources?

Singular routes* are a little different – they are written as singular resource . Declaring a resource or resources generally corresponds to generating many default routes. resource is singular. resources is plural.


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.


                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)

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!


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 }

2) :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]