Home / Rails Style Guide Topics

Active Record Style: Models, Scopes, Callbacks and Queries

The documentation that used to be at this address is no longer published, and its source was never released under an open license, so it is not reproduced here. This page is an independent guide to the same topic, written for this archive. It is not the project's documentation and is not affiliated with its authors.

Active Record makes database work feel like ordinary Ruby, which is both its strength and its risk. These conventions keep models readable and queries efficient as an app grows.

A predictable model layout

Order the contents of a model the same way everywhere so readers know where to look:

class Order < ApplicationRecord
  # constants
  STATUSES = %w[pending paid shipped cancelled].freeze

  # associations
  belongs_to :customer
  has_many :line_items, dependent: :destroy

  # validations
  validates :status, inclusion: { in: STATUSES }
  validates :total_cents, numericality: { greater_than_or_equal_to: 0 }

  # scopes
  scope :recent, -> { where(created_at: 30.days.ago..) }
  scope :paid, -> { where(status: "paid") }

  # public methods
  def paid?
    status == "paid"
  end
end

Scopes and queries

Avoiding N+1 queries

# one query for orders, then one per customer
Order.recent.each { |order| puts order.customer.name }

# two queries in total
Order.recent.includes(:customer).each { |order| puts order.customer.name }

Validations and constraints

Model validations give friendly errors, but only the database can guarantee integrity under concurrent requests. Back important rules with constraints: a NOT NULL column alongside presence, and a unique index alongside uniqueness.

Use callbacks sparingly

Callbacks are fine for keeping a record internally consistent, such as normalising an email before validation. They are a poor home for side effects like sending emails or calling external APIs, because those then run in every test and every console session. Move that work to a service object or a background job triggered explicitly.

Migrations

Keep migrations reversible, avoid referencing model classes inside them (the model may change later), and add indexes for foreign keys as part of the same migration that adds the column.

More on Rails Style Guide Topics

Explore the archive