Active Record
Active Record is the M in Rails MVC: one class per table, one instance per row, one method per column. It implements the Active Record pattern (a row knows how to persist itself), not the Data Mapper pattern — which explains both its ergonomics and its critics.
The 60-second answer
Section titled “The 60-second answer”“Active Record maps Post to the posts table, and migrations are versioned Ruby files that change the schema. Associations — belongs_to, has_one, has_many, has_many through: and polymorphic belongs_to ..., polymorphic: true — exist to give you composable query methods, not just accessors. Validations run in Ruby before save; database constraints are the real guarantee, so you want both. Callbacks hook the lifecycle but cascade and are hard to test, so keep them small and prefer after_commit. The two production killers are N+1 queries, fixed with includes, and missing indexes, fixed in a migration.”
Models and migrations
Section titled “Models and migrations”class CreatePosts < ActiveRecord::Migration[7.1] def change create_table :posts do |t| t.references :author, null: false, foreign_key: { to_table: :users } t.string :title, null: false t.string :slug, null: false t.datetime :published_at t.timestamps end
add_index :posts, :slug, unique: true add_index :posts, [:published_at, :created_at] endendt.references creates an index by default in modern Rails, so do not add a duplicate. foreign_key: true creates a real constraint — the only thing that survives a concurrent write. Never edit a migration that has already run in production; add a new one.
Associations
Section titled “Associations”| Declaration | Meaning |
|---|---|
belongs_to :author |
This row holds author_id; presence validated since Rails 5 |
has_many :comments |
The other table holds post_id |
has_many :tags, through: :taggings |
A join model you control: extra columns, validations |
belongs_to :commentable, polymorphic: true |
commentable_id + commentable_type |
class Comment < ApplicationRecord belongs_to :commentable, polymorphic: trueend
class Post < ApplicationRecord has_many :comments, as: :commentableend
post.comments.create!(body: "Nice") # sets commentable_type = "Post"A polymorphic association cannot have a database foreign key to two tables: you lose referential integrity, and commentable_type is a string that must stay in sync with class names. When integrity matters, use two nullable FKs with a check constraint. has_many through: beats habtm because the join model can carry data (role, position) and validations.
Validations and callbacks
Section titled “Validations and callbacks”class User < ApplicationRecord validates :email, presence: true, uniqueness: { case_sensitive: false } before_validation :normalise_email after_create_commit :send_welcome_email after_commit :reindex, on: [:create, :update]enduniqueness: true is a race — two requests can both pass. The unique index is the guarantee; keep both, the validation for the message and the index for the invariant. save runs validations; update_column, insert_all and update_all skip them. create! and save! raise ActiveRecord::RecordInvalid instead of returning false.
Prefer after_*_commit for side effects: after_create fires inside the transaction, so a later rollback leaves the email sent. Callbacks cascade — saving A saves B, firing B’s callbacks, touching C. Observers were removed from core in Rails 4 and live in the rails-observers gem; the modern answer is a service object.
Queries, STI and polymorphic
Section titled “Queries, STI and polymorphic”scope :by_author, ->(user) { where(author: user) }
Post.published.recent.by_author(user).limit(10)Post.find(1) # raises RecordNotFoundPost.find_by(slug: "hello") # nil if missingPost.where(id: 1) # empty relation, never raisesA scope must return a relation — one whose body can return nil breaks the chain, so wrap it in all.
class Account < ApplicationRecord; endclass SavingsAccount < Account; end # accounts table has a `type` string columnSTI stores several classes in one table discriminated by type: right when subclasses share almost all columns and differ in behaviour, wrong when they diverge into nullable columns. A polymorphic association is the inverse — one row belonging to any of several parents — and buys that flexibility at the cost of database integrity.
N+1 and eager loading
Section titled “N+1 and eager loading”Post.limit(20).each { |post| puts post.author.name } # 1 + 20 queriesPost.includes(:author).limit(20).each { |post| puts post.author.name } # 2 queriesincludes— Rails picks a second query (preload) or aLEFT OUTER JOIN(eager_load).preload— always two queries; cannot filter on the association.eager_load— always a join; required when you filter by the association.references— forces the join when combiningincludeswith a string condition.
Transactions and locking
Section titled “Transactions and locking”Order.transaction do order.update!(status: "paid") Inventory.reserve!(order)end
account.with_lock { account.update!(balance: account.balance - 100) } # SELECT ... FOR UPDATEAny exception rolls back and propagates; ActiveRecord::Rollback rolls back silently on purpose. update! raises while update returns false — the non-bang version inside a transaction commits with half the work done. Optimistic locking uses a lock_version column and raises StaleObjectError on a conflicting save; pessimistic locking serialises a read-modify-write. Both only hold inside a transaction.
Follow-up questions
Section titled “Follow-up questions”- What is the difference between
includes,preloadandeager_load? - Why is a uniqueness validation not enough?
- What does
after_commitprotect you from, and what is the risk of doing work there? - When would you choose STI over a polymorphic association?
- Why does
update_allskip validations and callbacks, and when is that correct?
Common traps
Section titled “Common traps”dependent: :destroyon a large association. Loads every child and runs every callback;delete_allis one statement when callbacks are not needed.- Side effects in
after_create. They run inside the transaction and survive a rollback. Post.all.eachon a big table. Usefind_eachorin_batches.countin a loop. A query per iteration; usecounter_cacheor one grouped query.- Assuming
savereturns the record. It returnstrue/false; usesave!orcreate!.