Skip to content

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.

“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.”

db/migrate/20240115120000_create_posts.rb
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]
end
end

t.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.

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: true
end
class Post < ApplicationRecord
has_many :comments, as: :commentable
end
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.

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]
end

uniqueness: 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.

scope :by_author, ->(user) { where(author: user) }
Post.published.recent.by_author(user).limit(10)
Post.find(1) # raises RecordNotFound
Post.find_by(slug: "hello") # nil if missing
Post.where(id: 1) # empty relation, never raises

A scope must return a relation — one whose body can return nil breaks the chain, so wrap it in all.

class Account < ApplicationRecord; end
class SavingsAccount < Account; end # accounts table has a `type` string column

STI 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.

Post.limit(20).each { |post| puts post.author.name } # 1 + 20 queries
Post.includes(:author).limit(20).each { |post| puts post.author.name } # 2 queries
  • includes — Rails picks a second query (preload) or a LEFT 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 combining includes with a string condition.
Order.transaction do
order.update!(status: "paid")
Inventory.reserve!(order)
end
account.with_lock { account.update!(balance: account.balance - 100) } # SELECT ... FOR UPDATE

Any 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.

  1. What is the difference between includes, preload and eager_load?
  2. Why is a uniqueness validation not enough?
  3. What does after_commit protect you from, and what is the risk of doing work there?
  4. When would you choose STI over a polymorphic association?
  5. Why does update_all skip validations and callbacks, and when is that correct?
  • dependent: :destroy on a large association. Loads every child and runs every callback; delete_all is one statement when callbacks are not needed.
  • Side effects in after_create. They run inside the transaction and survive a rollback.
  • Post.all.each on a big table. Use find_each or in_batches.
  • count in a loop. A query per iteration; use counter_cache or one grouped query.
  • Assuming save returns the record. It returns true/false; use save! or create!.