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.

# config/routes.rb

resource :user do
  resource :image
end

Let’s say, Post resources can have image. It can be defined in routes as given below.

# config/routes.rb

resources :posts do
  resource :image
end

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.

# config/routes.rb

concern :imageable do
  resource :image
end

resource :user, concerns: :imageable
resources :posts, concerns: :imageable

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.

# config/routes.rb

concern :imageable do
  resource :image
end

concern :commentable do
  resources :comments
end

resources :posts, concerns: [:imageable, :commentable]
resource :user, concerns: [:imageable]

The above code is similar to routes defined below.

resources :posts do
  resource :image
  resources :comments
end

resources :user do
  resource :image
end

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