Lesson 4 of 9 · 27m
Modeling Invariants with ActiveRecord
Use validations, associations, transactions, and database constraints together so Rails models encode real business truth rather than convenient object graphs.
Rails validations are not data integrity. They are user-experience guards. Real integrity lives in invariants that remain true when two requests race, a console command runs, an import script bypasses the UI, or a developer writes a clever service object at midnight. Senior Rails work means deciding which truth belongs in Ruby and which truth must exist in Postgres.
Start with the invariant, not the form
"An invoice has at most one active payment intent" is a business invariant. A validation can help, but the database needs a unique partial index:
class AddUniqueActivePaymentIntent < ActiveRecord::Migration[8.0]
disable_ddl_transaction!
def change
add_index :payment_intents, :invoice_id, unique: true, where: "status = 'active'", algorithm: :concurrently, name: "idx_payment_intents_one_active_per_invoice"
end
endWithout it, two concurrent checkouts can both pass validation and create duplicates.
Associations are API contracts
Be explicit about inverse relationships and dependent behavior:
class Account < ApplicationRecord
has_many :memberships, inverse_of: :account, dependent: :destroy
has_many :users, through: :memberships
enddependent: :destroy is not harmless. It instantiates callbacks and can delete large trees synchronously. dependent: :delete_all skips callbacks. Foreign keys with cascading behavior push the decision into the database. Choose deliberately, and never let a user deletion surprise you by enqueueing ten thousand callback jobs.
Transactions make multi-write invariants real
If two writes must succeed or fail together, say so:
Invoice.transaction do
invoice.lock!
invoice.update!(status: "finalized", finalized_at: Time.current)
invoice.line_items.update_all(tax_locked: true)
InvoiceEvent.create!(invoice:, actor:, kind: "finalized")
endlock! matters when the invariant depends on the current row state. Without it, two transactions can read the same stale status and both decide they won.
Callbacks are a scalpel, not an organizing principle
Use callbacks for small, intrinsic consequences such as normalizing a value. Avoid callbacks that send email, charge money, mutate remote systems, or create hidden coupling. If order.save can call a payment gateway, your test suite and incident response both become harder.
Service objects earn their keep at coordination boundaries
A plain Ruby object is useful when a workflow spans models, jobs, external APIs, or complex authorization. It should expose a narrow contract and return explicit results. It should not become a dumping ground named UserService with forty unrelated methods.
Field notes
validates_uniqueness_ofhas a race condition; use database unique indexes for real uniqueness.touch: truecan invalidate cache and trigger cascading writes in places you did not expect.update_columnskips validations and callbacks; use it only when bypassing them is the point.after_commitis the right hook for work that must not happen if the transaction rolls back, but prefer explicit orchestration for critical flows.
Was this lesson helpful?