Rails Routes member vs collection
Rails routes on resources support member routing as well as collection routing. Member routes act on a member of the resource. Collection routes acts on resources in general.
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.
resource :posts do
post :archive, on: :member
endThis will generate a route on a member of post resource
to archive a post.
We can print routes defined by rails using command
rails routes.
archive_post POST /posts/:id/archive(.:format) /posts#archiveAs we can see from the rails routes output above,
it has created a route that accepts :id parameter
and
call archive action on posts controller.
Collection Routes
Collection routes
can be defined for actions
that are performed on collection of the resource.
Taking same example as above,
searching a particular post is an action
that is performed on collection of posts.
Thus, it needs to be defined on posts resource as a collection.
resource :posts do
get :search, on: :collection
endThis will generate a route as given below.
search_posts GET /posts/search(.:format) /posts#searchAs we can see,
collection routes don’t take any :id parameter
in input.
It just acts on an entire collection of posts resource.
Define multiple member / collection routes together
If we want to define multiple
member or collection routes
for a resource,
then
we can use block to define all together.
resource :posts do
member do
post :archive
get :inactivate
end
collection do
get :search
post :upload
end
endReferences
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox