Table of contents
1.
What Are Rails Concerns?
2.
Why the Hype?
2.1.
Anatomy of a Rails Concern
2.2.
Directory Structure
2.3.
File Structure
3.
Implementing Concerns
3.1.
Under the Hood Mechanics
4.
Advanced Topics in Rails Concerns
4.1.
Class Methods and Scopes
4.2.
Callbacks and Validations
5.
Frequently Asked Questions
5.1.
Is it mandatory to put concerns in the concerns directory?
5.2.
Can concerns have their own database tables?
5.3.
Do concerns impact performance?
6.
Conclusion
Last Updated: Feb 5, 2025
Easy

Rails Concerns

Author Lekhika
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

As the saying goes, "With great power comes great responsibility." While Ruby on Rails (or simply, Rails) offers an unparalleled toolkit for rapid web development, managing the intricacies of a growing codebase can quickly become overwhelming. Enter Rails Concerns—a built-in feature designed to help you write cleaner, modular, and reusable code. 

Rails Concerns

This article will serve as an in-depth guide to mastering Rails Concerns, a tool that can dramatically improve your coding experience.

What Are Rails Concerns?

Rails Concerns are a specialized type of Ruby module that allows you to encapsulate related functionalities into a single, reusable unit. This unit can then be included in multiple places within your Rails application, such as models, controllers, and even views.

Why the Hype?

Understanding the benefits of Rails Concerns can provide insights into why they are so crucial:

  • DRY Code: Don't Repeat Yourself is a software development principle. Concerns let you adhere to it by eliminating redundant code.
     
  • Modularity: Concerns offer a way to group related functions together, making it easier to understand, modify, and maintain code.
     
  • Reusability: Because Concerns are modules, they can be included in multiple parts of your application, thus enhancing code reuse.

Anatomy of a Rails Concern

Creating a Rails Concern is simple and usually follows a standard structure:

Directory Structure

Navigate to your Rails application directory.

Inside the app folder, you'll find folders for models (app/models) and controllers (app/controllers).

Create a new directory named concerns within app/models or app/controllers.

File Structure

Inside the concerns folder, create a Ruby file. Let's call it taggable.rb.

# app/models/concerns/taggable.rb


module Taggable
  extend ActiveSupport::Concern


  included do
    has_many :tags
  end


  def list_tags
    self.tags.pluck(:name).join(", ")
  end
end

This example defines a Taggable concern with a relationship (has_many :tags) and an instance method (list_tags).

Implementing Concerns

Once you've created a Concern, it's time to include it in your desired models or controllers. The process is straightforward:

class Article < ApplicationRecord
  include Taggable
end

Under the Hood Mechanics

When you include the Taggable concern in your Article model, Rails essentially "mixes in" all the methods, relationships, and hooks defined in the concern. Now, any instance of the Article class can use the list_tags method, and the has_many :tags relationship is automatically set up.

Advanced Topics in Rails Concerns

Concerns are not limited to instance methods and relationships. They can also define class methods, scopes, and even add callbacks.

Class Methods and Scopes

In the Concern, you can define class methods using the class_methods block:

module Taggable
  extend ActiveSupport::Concern

  included do
    has_many :tags
  end

  class_methods do
    def tagged_with(name)
      joins(:tags).where(tags: { name: name })
    end
  end
end

Now, you can easily filter articles tagged with a specific name:

filtered_articles = Article.tagged_with("Ruby")

Callbacks and Validations

Concerns can also include ActiveRecord callbacks or validations. Imagine you want to ensure that an article has at least one tag:

module Taggable
  extend ActiveSupport::Concern


  included do
    has_many :tags
    validate :must_have_at_least_one_tag
  end


  def must_have_at_least_one_tag
    errors.add(:tags, "must exist") if tags.empty?
  end
end

Frequently Asked Questions

Is it mandatory to put concerns in the concerns directory?

No, it's a convention but not a requirement. You can place concerns anywhere, but following conventions makes your codebase easier to navigate.

Can concerns have their own database tables?

No, concerns are modules encapsulating functionalities and are not tied to database tables. They enhance models that do.

Do concerns impact performance?

Generally, concerns don't negatively impact performance. They are a way to organize code and make it more manageable.

Conclusion

Rails Concerns are like spices in cooking—used correctly, they can dramatically elevate your dish, or in this case, your code. They offer an elegant way to encapsulate related functionalities into reusable modules. This makes your application easier to develop, easier to read, and ultimately, easier to maintain. Given these benefits, mastering Rails Concerns is not just a recommendation; it's a necessity for every Rails developer.
For more information, refer to our Guided Path on Coding Ninjas Studio to upskill yourself in PythonData Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more! 

Head over to our practice platform, CodeStudio, to practice top problems, attempt mock tests, read interview experiences and interview bundles, follow guided paths for placement preparations, and much more!

Live masterclass