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.
This 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
.
As 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.
This will generate a route as given below.
As 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.
References
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox