Rails routes concerns
Rails supports concerns in Routes. Concerns can be defined in Rails routes to be able to have reusable routes.
Sometimes, we need similar routes for different resources. Let’s take an example.
Let’s say, we have a User
and Post
entity.
User can have an image. Thus, we need image resource for user resource routes.
It can be defined in
routes
as given below.
Let’s say, Post
resources can have image.
It can be defined in routes as given below.
As we can see, the routes defined above, are not very DRY.
Use of concerns in Rails routes
We can use Routing concerns, to avoid repeating same routes defined.
Here, we have defined a concern imageable
.
It is used with resource user
and posts
resources.
As the key concerns
suggests,
it can be used to have multiple concerns for a resource.
Multiple concerns in routes
We can have multiple concerns, used for a resource or resources.
Let’s say, we have imageable
and commentable
concerns as given below.
The above code is similar to routes defined below.
Here, resources posts
will use both concerns imageable
and commentable
.
Resource user
will only have image
resource because of single concern used with it.
References
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox