Nowy standard. Twoje centrum tworzenia inteligentnego, szybkiego i zrównoważonego oprogramowania AI

Zobacz teraz
Abstract illustration of a striped data store with drawers connected by a single link to a separate stack of records, representing a Rails repository layer between Active Record models and business logic

How to Use Ruby on Rails Repositories With the Active Record Model

Hubert Białęcki
|   Zaktualizowano 15 lis 2026

A Ruby on Rails repository is a class that encapsulates all database calls for a single model, so services and controllers never query Active Record directly.

One tech lead's Rails project had models bloated with validations, callbacks, scopes, and business logic, and the team's answer was to add a repository layer.

The Rails repository pattern keeps models and controllers thin and makes business logic easy to unit test, without leaving Active Record behind.

Executive Summary

Each Active Record model loads and saves itself, keeping early development fast but making later changes risky. A repository layer moves database access into dedicated classes, which services receive and tests can replace with fakes.

Wrapping Active Record is the cheapest version of the pattern, though developers can still bypass it. Splitting queries from commands, returning plain value objects, or switching to Sequel or ROM tightens the design when a codebase needs it.

What Is the Repository Pattern in Rails?

The repository pattern places a collection-like object between business logic and the database. Edward Hieatt and Rob Mee define a repository as an object that mediates between the domain and data mapping layers.

Rails defaults to a different approach. Its Active Record pattern lets each model load, validate, and save itself, speeding up early development and aligning with Rails' conventions. As an app grows, though, persistence code spreads across models, controllers, and services.

Repositories gather that code in one place. Microsoft describes repositories as classes that encapsulate the logic needed to access data sources, keeping the domain model independent of database technology. The same guidance notes that repositories make unit testing easier because tests can swap in mock data.

Every query then lives in a known file. Reviewers know where to look, and refactoring a query affects only one class.

Why Do Active Record Models Grow Too Large?

Active Record models grow because they accept every responsibility a developer hands them. A trimmed example from the tech lead's project shows how quickly that happens:

class Contact < ApplicationRecord
  after_destroy :do_something

  belongs_to :user
  belongs_to :category
  has_many :emails, dependent: :destroy

  validates :name, presence: true
  validate :some_custom_validator

  scope :eligible_for_email, ->(user_id) {
    joins(:category)
      .select("contacts.*, categories.title AS category_title")
      .where(emailed: false, unsubscribed: false, user_id: user_id)
  }

  def status
    emails.any? ? "Emailed" : "Never emailed"
  end

  private

  def do_something
    # A harmless callback, until it is not
  end

  def some_custom_validator
    # Can this record even be saved?
  end
end

Real models on the project ran three to four times longer. Each callback and scope made the next change riskier because a save could trigger side effects no one remembered.

Project goals were to separate database calls from business logic, create testable interfaces, keep models and controllers lightweight, and clarify responsibilities. Rewriting everything was off the table, so the plan moved in four steps. First, find every database call, then extract each one into a repository, cover it with tests, and finally shrink the model.

How Do You Build a Repository on Top of Active Record?

Create one repository per model the app queries or updates, and route every query through it. A class-level repository keeps the change small.

Larger domains can group models more effectively. Microsoft's guidance also recommends one repository per aggregate root, not one per database table. In Rails terms, a Contact and its Emails can share ContactRepository because emails belong to their contact and disappear with it.

class ContactRepository
  class << self
    def find_by(*attrs)
      Contact.find_by(*attrs)
    end

    def destroy(contact)
      contact.destroy
    end

    def eligible_for_email(user_id)
      Contact
        .joins(:category)
        .select("contacts.*, categories.title AS category_title")
        .where(emailed: false, unsubscribed: false, user_id: user_id)
    end
  end
end

Services receive the repository as a dependency, so a unit test can pass a fake one.

class SendEmail
  def initialize(current_user_id, repo: ContactRepository)
    @contacts_to_email = repo.eligible_for_email(current_user_id)
  end

  def call
    # Send emails to @contacts_to_email
  end
end

Controllers call the repository as well, which keeps them free of query logic.

module Api
  module V1
    class ContactsController < ApiController
      def destroy
        contact = ContactRepository.find_by(id: params[:id])
        ContactRepository.destroy(contact)
        head :no_content
      end
    end
  end
end

The scope moved from the model to the repository, so the model shrank to associations and validations. Unit tests for SendEmail can then skip the database entirely.

How Do You Test a Service With a Fake Repository?

Pass a fake object that answers the same methods as the production repository. Your service never notices the difference, and the test never opens a database connection.

class FakeContactRepository
  attr_reader :requested_user_id

  def eligible_for_email(user_id)
    @requested_user_id = user_id
    []
  end
end

class SendEmailTest < ActiveSupport::TestCase
  test "asks the repository for the current user's contacts" do
    repo = FakeContactRepository.new
    SendEmail.new(42, repo: repo)
    assert_equal 42, repo.requested_user_id
  end
end

Tests like this run in milliseconds, so a team can keep hundreds of them in the suite. Each fake also documents the contract by listing exactly which repository methods a service depends on. Keep a smaller set of integration tests that hit a live database, and point them at the repository itself.

Contract drift is the main risk. Whenever a real repository method changes its arguments, the fake must change too, or the unit test will keep passing on an outdated interface. A shared test that runs the same examples on both classes catches this early.

How Do Repositories Handle Transactions and N+1 Queries?

Both concerns belong inside the repository, where they stay visible and consistent. Rails describes transactions as protective blocks in which SQL statements become permanent only if they all succeed as a single atomic action. Any repository method that changes multiple records should wrap those changes in a single transaction.

class ContactRepository
  class << self
    def move_to_category(contact_ids, category)
      Contact.transaction do
        Contact.where(id: contact_ids).find_each do |contact|
          contact.update!(category: category)
        end
      end
    end

    def with_emails(user_id)
      Contact.where(user_id: user_id).includes(:emails)
    end
  end
end

Because update! raises an error on failure, a single invalid contact rolls back the entire batch. The second method targets the N+1 queries antipattern, in which one query loads a set of records and another query runs for each record. Putting includes in the repository means every caller gets eager loading by default. Callers no longer need to remember which associations to preload.

What Are the Trade-offs of Rails Repositories?

Repositories wrapped around Active Record isolate queries and simplify tests, yet they rely on developers to keep using them. That reliance is the main difference between this light version and a strict data mapper. Below is what the project gained and what remained open:

Gains

Open issues

All database code sits in repositories

Repositories still return Active Record objects

Services and controllers stay thin

Developers can call the model directly and bypass the layer

Repositories are easy to mock in unit tests

Callbacks still fire on save and destroy

Models shrink to associations and validations

The design depends on code review and team habits

The returned object is the weak spot: an Active Record model can save itself, letting rushed developers bypass the repository. Saving through the repository still triggers callbacks. Code review and a custom RuboCop rule can catch direct model queries outside repositories. For larger codebases, Packwerk, released by Shopify in 2020, detects dependency and privacy violations between Ruby file groups.

How Can You Push the Repository Pattern Further?

The light version still depends on team discipline, since returned models can save themselves and callbacks still fire. The original project treated it as unfinished and listed three improvements, which a team can adopt one sprint at a time.

1. Split Queries From Commands

Separate repositories that read data from those that modify it, for example, ContactQueries and ContactCommands. Readers can return lightweight objects, while writers handle validation and transactions. The split is optional, but it clarifies intent in large domains.

2. Return Plain Entities From Repositories

Repositories can return plain value objects, so only the repository talks to the database. Ruby's built-in Data class provides simple classes for immutable values without extra gems.

ContactEntity = Data.define(:id, :name, :category_title, :status)

Gems from the dry-rb family provide typed structs for teams that need validation of entity attributes.

3. Replace Active Record in the Data Layer

For full control, a repository can use a different persistence library. Sequel describes itself as a simple, flexible SQL toolkit for Ruby, and ROM says its repositories handle data access while business logic works with plain Ruby objects. Both give up some Rails conveniences, such as generators and tight form integration, so weigh the switch carefully.

Hanami shows where that road leads. Its 2.2 release in November 2024 built a full database layer on ROM. Relations hold queries, repos serve as the app's database interface, and structs act as plain return values. Hanami's release notes say structs help avoid accidental N+1 queries because they hold no live database connection.

Steps one and two keep Active Record and the Rails conveniences around it. Step three gives up those conveniences for full control, so it suits codebases whose persistence rules justify the switch.

When Should a Rails Team Skip Repositories?

Skip repositories in small apps, prototypes, and CRUD-heavy admin tools, where Active Record conventions save time. Add the layer later, one model at a time, as on the original project. Short-lived prototypes gain little from indirection. New developers expect plain Rails models, which Rails 8.1 (October 2025) still builds around. The pattern has critics outside Rails, too: Jimmy Bogard told Microsoft's architecture guide that repositories hide important details of the persistence layer, and the guide leaves the decision to each team.

Introduce the layer when models grow hard to read, when business rules need fast unit tests, or when several services share complex queries. Inherited codebases often already meet that trigger. The layer fits neatly into a wider cleanup once developers and the client agree on refactoring priorities.

Key Takeaways

  • One repository per model, or per aggregate in larger domains, gathers all related queries and writes, which slims down models and controllers.

  • Fake repositories make service tests fast, and transactions and eager loading belong inside the repository.

  • Returned Active Record objects let developers bypass the layer, so code review matters.

  • Query and command splits, Ruby Data entities, or Sequel and ROM harden the layer further.

  • Small apps and admin tools usually work better with plain Active Record conventions.

Add Structure When the Model Stops Being Simple

Rails rewards convention early and structure later. Repository layers bring in that structure at low cost, because they wrap Active Record and leave the rest of the stack in place. The sooner a growing team decides where queries live, the cheaper each later refactor becomes.

Teams weighing a repository layer, or untangling a large Rails monolith, can work with Monterail's Rails engineers. Schedule a Rails architecture consultation with Monterail.

Rails Repository Pattern FAQ

Hubert Białęcki avatar
Hubert Białęcki
Head of Technology at Monterail
Linkedin
As Monterail’s Head of Technology, Hubert brings a unique blend of technical expertise and strategic leadership to drive innovation and organizational growth. A graduate of Wrocław University of Science and Technology, Hubert has carved an impressive career path from JavaScript developer to technology executive, demonstrating both technical mastery and exceptional leadership capabilities. He excels at understanding complex organizational dynamics and implementing strategic changes that enhance team performance and company development.