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
- Use scopes for reusable query fragments and keep each one small so they chain naturally:
Order.paid.recent. - Prefer hash conditions to SQL strings. When you need SQL, use placeholders, never string interpolation of user input.
- Use
find_eachwhen iterating over large tables so records load in batches. - Reach for
pluckwhen you only need column values, not full objects.
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.