There is a strong chance you’ve encountered Rails Concerns if you’ve been using Rails for a while. It can be confusing to understand where it fits into your Rails application and how best to make use of it. This is what we’ll be covering in this tutorial: what Rails Concerns are, why they exist, and their use cases.
What are Rails Concerns? In simple terms, a concern is a module. First, let’s review what a module is. A module is a collection of methods, constants, and class variables. Typically, modules can be used for two things: To share functionality across multiple places, such as classes; As namespaces. For our use case, we’ll focus on sharing functionality across multiple places. You do this by including the module in the places where you need such functionalities. You can think of a module as a bucket of related behaviors (methods) or data (attributes). These behaviors and attributes can then be used across different classes (or modules).
Here is what a concern looks like:
<pre>require "active_support/concern" module M extend ActiveSupport::Concern included do scope :disabled, -> { where(disabled: true) } end class_methods do ... end end</pre>
If we’re writing an equivalent without using Rails concern, ActiveSupport::Concern, it will look like this:
<pre>module M def self.included(base) base.extend ClassMethods base.class_eval do scope :disabled, -> { where(disabled: true) } end end module ClassMethods ... end end</pre>
In the code above, you can see that Rails Concern gives us a cleaner interface to work with. You can also see that we have what looks like a block: included and class_methods. class_methods in the concern defines class methods that will be available on the including class. These methods can be accessed on the class itself, rather than on instances of the class. included is a callback method that allows you to include code as if it were written directly in the including class. It gives you the ability to modify the class itself when the concern is included. It’s as if the code inside the included block has been pasted into the class where the concern is included.
Why do they exist? When we say a concern is a module, it means that, like a module, a concern makes it possible to share functionality across different classes in a Rails application. Here is a snippet from Rails Guides: Concerns are a way to make large controllers or models easier to understand and manage. This also has the advantage of reusability when multiple models (or controllers) share the same concerns. Concerns are implemented using modules that contain methods representing a well-defined slice of the functionality that a model or controller is responsible for. In other languages, modules are often known as mixins. If you have a piece of code that is used in different places in your code base, it will be helpful to abstract it into a concern.
Let’s say I have different scopes that I use in different models:
<pre>scope :created, -> { where(status: 'created') } scope :updated, -> { where(status: 'updated') } scope :deleted, -> { where(status: 'deleted') } scope :from_date, ->(date) { where(T.unsafe(arel_table)[:created_at].gteq(date)) } scope :to_date, ->(date) { where(arel_table[:created_at].lteq(date)) }</pre>
I can move that into a concern, which I can then use across the models involved. When should you use them? As mentioned above, you can use Rails Concerns when handling code reusability. It’s also common to make use of it for things like validation and error handling. For example, you can have an error handler like this:
<pre>module ErrorHandlerConcern extend ActiveSupport::Concern included do rescue_from(Unauthorized) do |exception| render json: { errors: "Unauthorized" }, status: 401 end rescue_from(UnprocessableEntity) do |exception| render json: { errors: "Unprocessable Entity" }, status: 422 end rescue_from(BadRequest) do |exception| render json: { errors: "There's something wrong with your request" }, status: 400 end rescue_from(Forbidden) do |_exception| render json: { errors: "You are not allowed" }, status: 403 end rescue_from(ActiveRecord::RecordNotFound) do |_exception| render json: { errors: "Record not found" }, status: 404 end end end</pre>
The code snippet above creates an error handler that rescues from certain errors. The rescue blocks are in the included block. This can then be included in the ApplicationController since this is something I’ll want to make use of across my application. The same applies to validations or authorization.
How should you use them? By default, the Rails application comes with a directory for concerns. You’ll see this in the controllers and models directories. Thus, you’ll want to place concerns that are related to models in app/models/concerns and that of controllers in app/controllers/concerns.
In one of my projects, I have a concern called VersionConcern that looks like this:
<pre>module VersionConcern extend ActiveSupport::Concern included do scope :active, -> { where(deleted_at: nil) } scope :deleted, -> { where.not(deleted_at: nil) } end class_methods do def delete_all_records update_all(deleted_at: Time.current) end def restore_all_records update_all(deleted_at: nil) end end end</pre>
This concern makes it possible for me to scope records based on whether they are active or deleted. To make use of this in a book model, I only need to include the concern in the model like this:
<pre>class Book < ApplicationRecord include VersionConcern belongs_to :author, class_name: 'User', foreign_key: 'user_id' ... end</pre>
If I want to fetch the active books for a user, I can do this:
<pre>Books.find_by(author_id: current_user.id).active</pre>
We can also make use of the class methods like so; Book.delete_all_records.
Pitfalls While Rails concerns help with reducing duplication, it is not the only “tool” out there. You can also create a service that holds this common code. It is important to know that Concerns are inheritance. Therefore, for example, if you check the lookup path of .active methods, you’ll see that VersionConcern is included. If you are concerned about that, you might want to consider something else, like making use of a service. Concerns are, however, a helpful tool to have in your Rails toolkit.
Conclusion While you might not necessarily use Concerns every time, it’s important to know what they do. In this tutorial, we’ve learned about the similarity between concerns and modules, why we have them, and how we can use them.