Member vs Collection in Rails Routes

Difference between the use cases of Member and Collection in Rails Router

Tushar Adhao
2 min readNov 19, 2019

There are different ways of defining Rails routes and the behavior of the route depends according to the options used along with it. So let's say, a route can have a unique field :id or :slug to navigate to some specific object page (ex. show page) and another route may not have any unique field as it may be displaying some listing of data (ex. index page). Considering the same case, the two terms can be differentiated in a simple way as :member is used when a route has a unique field :id or :slug and :collection is used when there is no unique field required in the route. Let’s look through the actual use case for each of them.

Collection

Let’s consider a condition where a route with URL ‘/homes/post’ is required. There is no specific :id or :slug is required in the route which is a basic condition for using :collection for the route.

Now, these routes can be defined as, get ‘homes/post’, to: ‘homes#post, as: :post_homes’ and another way to define the same route can be given as,

config/routes.rbRails.application.routes.draw do
resources :homes do
get :post, on: :collection
end
end

So that the routes available can be given as,

terminal=>$ rake routes | grep postPrefix      Verb   URI Pattern            Controller#Actionpost_homes  GET    /homes/post(.:format)  homes#post

Note : For defining multiple routes using collection can be given as,

config/routes.rbRails.application.routes.draw do
resources :homes do
collection do
get :post
post :comment
end
end
end

Member

A similar example can be taken to elaborate :member just the difference could be in using a unique field of :id given as get ‘homes/:id/post’, to: ‘homes#post', as: :post_home and another way to define the same route can be given as,

config/routes.rbRails.application.routes.draw do
resources :homes do
get :post, on: :member
end
end

So that the routes available can be given as,

terminal=>$ rake routes | grep postPrefix     Verb  URI Pattern                 Controller#Actionpost_home  GET   /homes/:id/post(.:format)   homes#post

Note 1 : For defining multiple routes using member can be given as,

config/routes.rbRails.application.routes.draw do
resources :homes do
member do
get :post
post :comment
end
end
end

And that wraps this section which includes the use case for Member and Collection in Rails Router.

--

--

Tushar Adhao

Software artist spreading nuggets of coding gold and sometimes philosophy too.