Active Record done well: models, migrations and queries that stay fast and correct
TL;DR
Difficulty: Intermediate
The data model is the hardest part of a Rails application to change later, so get it right from the first migration.
- The three writers test: the form, the shortcut and the twin. Validations stop the form. Only database constraints (NOT NULL, foreign keys, unique indexes, check constraints) stop the shortcut and the twin. Do both.
- A callback may tidy its own row. It may not talk to the world: send emails and texts from visible code, through a job.
- Queries follow the shape of the page, not the size of the data. includes, preload and a counter cache took the workshop board from 61 queries to 3, and a two row test keeps it there.
- Store money as whole cent, times in UTC, and let EXPLAIN tell you which index the database wants.
Active Record makes your database feel like Ruby, which is both its gift and its risk. This chapter builds the data model of an invented chain of bicycle repair workshops in Rails 7.1, table by table, and shows where each rule belongs: in the model, in the database, or in both. Then it takes one slow page from 61 queries to 3.
The question behind this chapter
"How do I model my data in Rails so that it stays fast and correct as the application grows?"
It is the right question to ask early, because the data model is the part of an application that is hardest to change later. You can rewrite a page in an afternoon. Changing what a booking is, once 60,000 of them sit in production, takes a migration plan, a backfill and a quiet weekend.
This chapter is about Active Record, the part of Ruby on Rails that maps your database tables to Ruby objects. Everything here is written for Rails 7.1, the current version, on Ruby 3.3 and PostgreSQL 1612. It follows on from starting a new Rails application, where the database, money and time zone decisions were made, and from how a Rails application is structured, which showed where models and migrations live.
The example runs through the whole chapter. Freewheel Cycles is an invented chain of six bicycle repair workshops in Limerick (freewheelcycles.example), founded by Niamh. It has 38 mechanics, about 1,150 repair bookings a week, 9,000 active customers and 2,400 spare parts in stock. Its two developers, Aisling and Cian, are replacing spreadsheets and a rented booking widget with their own Rails application. The company and the people are made up. The code is real and runs on Rails 7.1.
Three rules to carry through the chapter
The Rails Guides explain every method in this chapter well. What they do not give you is a way to decide. So here are three rules of thumb I will use throughout, each earned in its own section below.
- The three writers test. Every rule about your data will meet three writers: the form, the shortcut and the twin. The form is a person using your application, and validations handle it. The shortcut is anything that writes without validations: the console, a data import,
update_all, a second application. The twin is a second request arriving at the same moment as the first. If a rule must survive the shortcut and the twin, it belongs in the database as a constraint, not only in the model. - Queries follow the shape of the page, not the size of the data. A page that shows bikes and mechanics should need about one query per kind of thing it shows. If the number of queries grows when the number of rows grows, you have an N+1 problem, and you can test for it with two rows and twenty.
- A callback may tidy its own row. It may not talk to the world. Normalising an email address before saving is fine. Sending a text message from a callback is how you end up texting customers about a repair that was rolled back.
None of these is in the official guide in this form. They are my distillation of it, and each section shows the reasoning so you can disagree with it on evidence.
What Active Record is, and what it is not
Active Record is first a design pattern, named by Martin Fowler in Patterns of Enterprise Application Architecture in 2002. He describes it as "an object that wraps a row in a database table or view"3. The object carries the data of that row and the behaviour that belongs to it, and it knows how to load and save itself.
Rails took the pattern and built its object relational mapper (ORM) on it. An ORM is the layer that turns rows into objects and method calls into SQL. In Rails the library is also called Active Record, and the Rails Guides describe it as the M in model, view, controller4.
Two conventions do most of the work:
- A class called
Bookingmaps to a table calledbookings. A column calledstarts_atbecomes a method calledstarts_at. - The model does not list its columns. Rails reads them from the database schema when the application starts.
That second point surprises people coming from Django, where a model declares its fields in Python and makemigrations writes the migration from those declarations5. In Rails you write the migration, the database changes, and the model reads the result. Both are reasonable designs. The Rails way keeps one source of truth, the database. The Django way keeps the field list visible in the model file. The Django series builds this same schema with the Django ORM in its own chapter, so you can compare the two line by line.
One thing is worth saying plainly before any code. Your data will outlive your code. Freewheel's Rails application may be rewritten, split or replaced in ten years. The bookings, customers and invoices will still be there, and they will be read by reports, accountants and whatever comes next. That is why this chapter keeps pushing rules down into the database: the database is the part that stays.
Example: one booking as an object
Here is a Freewheel booking in the Rails console, bin/rails console, once the models below exist:
booking = Booking.find(4211)
# SELECT "bookings".* FROM "bookings" WHERE "bookings"."id" = $1 LIMIT $2
booking.starts_at # => Sat, 17 Feb 2024 09:00:00.000000000 GMT +00:00
booking.mechanic.name # => "Darragh" (a second query loads the mechanic)
booking.update!(starts_at: booking.starts_at + 30.minutes)
# UPDATE "bookings" SET "starts_at" = $1, "updated_at" = $2 WHERE "bookings"."id" = $3
Every line is plain Ruby, and every line becomes SQL. That is the whole promise of Active Record, and also its trap: SQL you do not see is SQL you do not count. Hold on to that for the section on N+1 queries.
Migrations, and the schema file as the record of truth
A migration is a Ruby file in db/migrate that changes the database schema one step at a time: create a table, add a column, add an index. Each file has a timestamp in its name, Rails records which ones have run, and bin/rails db:migrate runs the rest6.
After every migration, Rails writes the whole current schema to one file. By default that is db/schema.rb, a Ruby description of every table. The Migrations guide is clear about its status: the schema file, not the pile of old migrations, is how you rebuild a database, and bin/rails db:schema:load is faster and less error prone than replaying history6. Commit it to version control, always.
There is a second format. Setting config.active_record.schema_format = :sql makes Rails dump db/structure.sql instead, using the database's own tool (for PostgreSQL, pg_dump). The guide explains when you need it: schema.rb cannot express everything a database supports, such as triggers, sequences and stored procedures6.
My view: start with schema.rb, and switch to structure.sql the day you write your first execute with raw SQL in a migration for something the Ruby format cannot express. Check constraints, foreign keys, partial indexes and, in Rails 7.1 on PostgreSQL, exclusion and unique constraints are all expressible in Ruby, so many applications never need the switch7.
Example: Freewheel's first two migrations
Aisling generates the first tables:
bin/rails generate model Workshop name:string city:string
bin/rails generate model Mechanic workshop:references name:string email:string
Rails writes two migrations. She edits them before running anything, because the generator's defaults allow empty values:
# db/migrate/20240213090000_create_workshops.rb
class CreateWorkshops < ActiveRecord::Migration[7.1]
def change
create_table :workshops do |t|
t.string :name, null: false # NOT NULL: a workshop always has a name
t.string :city, null: false
t.timestamps
end
add_index :workshops, :name, unique: true
end
end
# db/migrate/20240213090100_create_mechanics.rb
class CreateMechanics < ActiveRecord::Migration[7.1]
def change
create_table :mechanics do |t|
# references adds workshop_id and an index; foreign_key adds the constraint
t.references :workshop, null: false, foreign_key: true
t.string :name, null: false
t.string :email, null: false
t.timestamps
end
add_index :mechanics, :email, unique: true
end
end
bin/rails db:migrate runs both and rewrites db/schema.rb. Cian, pulling the branch on his laptop, runs bin/rails db:prepare and gets an identical database. Neither of them edits schema.rb by hand.
The whole schema on one page
Before any more code, here is the whole model on one page. It covers the core of the application: booking, the workshop board, job cards and parts. Invoices and reporting come later in the series and build on these tables.
| Table | Belongs to | Key columns | Constraints in the database |
|---|---|---|---|
| workshops | name, city | name NOT NULL and unique | |
| mechanics | workshop | name, email | foreign key to workshops, email unique |
| customers | name, email, phone | email NOT NULL and unique | |
| bikes | customer | make, model, colour | foreign key to customers |
| bookings | customer, bike, mechanic, workshop | starts_at, ends_at, cancelled_at | one active booking per mechanic and start time, ends after it starts |
| job_cards | workshop, bike, mechanic, booking (optional) | status, part_usages_count, notes | status is one of four values, one card per booking |
| parts | sku, name, price_cents, stock_on_hand, reorder_level | sku unique, stock never below zero | |
| part_usages | job card, part | quantity | quantity above zero, one row per part per job card |
Two choices deserve a word. A job card points to a booking, but the booking is optional, because a customer can wheel a bike in without booking online. And the job card stores its own bike_id and mechanic_id rather than reaching through the booking, for the same reason: a walk in has no booking to reach through.
Example: the remaining migrations
class CreateCustomersAndBikes < ActiveRecord::Migration[7.1]
def change
create_table :customers do |t|
t.string :name, null: false
t.string :email, null: false
t.string :phone
t.timestamps
end
add_index :customers, :email, unique: true
create_table :bikes do |t|
t.references :customer, null: false, foreign_key: true
t.string :make, null: false
t.string :model, null: false
t.string :colour
t.timestamps
end
end
end
class CreateBookings < ActiveRecord::Migration[7.1]
def change
create_table :bookings do |t|
t.references :customer, null: false, foreign_key: true
t.references :bike, null: false, foreign_key: true
t.references :mechanic, null: false, foreign_key: true
t.references :workshop, null: false, foreign_key: true
t.datetime :starts_at, null: false
t.datetime :ends_at, null: false
t.datetime :cancelled_at # NULL means the booking is active
t.timestamps
end
# The twin request: only one active booking per mechanic and slot
add_index :bookings, [:mechanic_id, :starts_at], unique: true,
where: "cancelled_at IS NULL", name: "index_bookings_one_per_slot"
add_check_constraint :bookings, "ends_at > starts_at", name: "bookings_end_after_start"
end
end
class CreateJobCards < ActiveRecord::Migration[7.1]
def change
create_table :job_cards do |t|
t.references :workshop, null: false, foreign_key: true
t.references :bike, null: false, foreign_key: true
t.references :mechanic, null: false, foreign_key: true
# Optional (walk ins), but at most one card per booking
t.references :booking, foreign_key: true, index: { unique: true }
t.string :status, null: false, default: "waiting"
t.integer :part_usages_count, null: false, default: 0 # counter cache
t.text :notes
t.timestamps
end
add_check_constraint :job_cards,
"status IN ('waiting', 'in_repair', 'ready', 'collected')",
name: "job_cards_status_known"
end
end
class CreatePartsAndPartUsages < ActiveRecord::Migration[7.1]
def change
create_table :parts do |t|
t.string :sku, null: false
t.string :name, null: false
t.integer :price_cents, null: false # money as whole cent, never a float
t.integer :stock_on_hand, null: false, default: 0
t.integer :reorder_level, null: false, default: 0
t.timestamps
end
add_index :parts, :sku, unique: true
add_check_constraint :parts, "stock_on_hand >= 0", name: "parts_stock_not_negative"
create_table :part_usages do |t|
t.references :job_card, null: false, foreign_key: true
t.references :part, null: false, foreign_key: true
t.integer :quantity, null: false
t.timestamps
end
add_index :part_usages, [:job_card_id, :part_id], unique: true
add_check_constraint :part_usages, "quantity > 0", name: "part_usages_quantity_positive"
end
end
The unique index on bookings uses a where: clause, which makes it a partial index: cancelled bookings are left out, so a slot freed by a cancellation can be booked again. The PostgreSQL unique index on job_cards.booking_id allows any number of empty values, which is exactly what walk ins need.
Associations: how the tables know each other
An association is a declared relationship between two models. It gives you methods such as booking.mechanic and mechanic.bookings, and it tells Rails which foreign key column to use8. Four kinds cover most of an application:
belongs_tosits on the model whose table holds the foreign key. A booking belongs to a mechanic becausebookingshasmechanic_id.has_manyis the other side. A mechanic has many bookings.has_many :throughreaches across a join model that matters in its own right. A job card has many parts through part usages, and the part usage carries the quantity.has_oneishas_manywith at most one row. A booking has one job card.
Since Rails 5.0, belongs_to is required by default: a record whose parent is missing fails validation unless you write optional: true9. That default is right. It turns a forgotten parent into an error message instead of a silent nil.
The guide also says something easy to miss: belongs_to with optional: true does not ensure reference consistency, and depending on the use case you may need a foreign key at the database level as well8. The foreign_key: true in every migration above is that foreign key.
Example: the models for the core tables
# app/models/mechanic.rb
class Mechanic < ApplicationRecord
belongs_to :workshop
has_many :bookings, dependent: :restrict_with_error
has_many :job_cards, dependent: :restrict_with_error
end
# app/models/job_card.rb
class JobCard < ApplicationRecord
belongs_to :workshop
belongs_to :bike
belongs_to :mechanic
belongs_to :booking, optional: true # walk ins have no booking
has_many :part_usages, dependent: :destroy
has_many :parts, through: :part_usages
end
# app/models/part_usage.rb
class PartUsage < ApplicationRecord
belongs_to :job_card, counter_cache: true # keeps job_cards.part_usages_count
belongs_to :part
end
dependent: :restrict_with_error on the mechanic means Rails refuses to delete a mechanic who still has bookings, with an error on the record. The foreign key would refuse too, with a database exception. The model rule gives the manager a readable message, and the database rule makes sure nobody gets round it. That pairing is the theme of the next section.
Polymorphic associations, and when to avoid them
A polymorphic association lets one model belong to more than one other model through a pair of columns, an id and a type name: belongs_to :imageable, polymorphic: true stores imageable_id and imageable_type8.
It is handy, and Rails itself uses it: Active Storage, the file upload library, keeps a polymorphic join table so any model can have attachments10. When Freewheel adds before and after photos to job cards with has_many_attached :photos, that is a polymorphic association, and it is the right tool there.
The cost is that the database cannot hold a foreign key on a column that points to several tables. PostgreSQL has no idea that imageable_id 42 with type JobCard should exist in job_cards. The Active Storage guide even warns that renaming a model class means migrating the stored type names10.
My view: use polymorphism for infrastructure that genuinely attaches to anything (files, audit entries, comments everywhere), and avoid it for business relationships. If Aisling wanted notes on both bookings and job cards, two plain tables or two nullable foreign keys with a check constraint keep the database able to protect the data. Rails guides call it a "slightly more advanced twist"8. I call it a trade: flexibility for integrity. Make it knowingly.
Validations or constraints? Do both, and know why
A validation is a check in the model that runs before Rails saves a record: validates :email, presence: true. If it fails, nothing is written, and the record carries a readable error message for the form11.
A constraint is a rule inside the database: NOT NULL, a unique index, a foreign key, a check constraint. If it fails, the database refuses the write, and Rails raises an exception.
The Rails Guides are, honestly, of two minds here. The Migrations guide says the Active Record way puts intelligence in your models and that constraints in the database are "not recommended"6. The Validations guide, a few pages away, says a uniqueness validation alone can let two connections create duplicates, and that you must add a unique index to prevent it11. The second statement is the one that survives contact with production.
Here is the three writers test in full. For each rule, ask who could break it:
- The form. A person types something wrong. A validation catches it and shows a message. Constraints would catch it too, but with an exception instead of a message.
- The shortcut. A script, the console,
update_all,insert_all,update_columnor a CSV import. These skip validations by design. The Callbacks guide lists them and asks you to use them with caution12. Only a constraint holds. - The twin. Two requests at the same moment. Both run the uniqueness validation, both see no clash, both insert. Only a unique index holds.
If a rule only has to survive the form, a validation is enough. If it must survive all three, you need the constraint. And because people deserve readable messages, you usually want both.
Example: the Saturday morning double booking
Saturday morning is Freewheel's peak: 30% of the week's online bookings arrive between Friday 6pm and Saturday noon. Two customers open the booking page on Friday evening and both pick mechanic Darragh at 9am on Saturday. Both press "Book" within the same second.
Aisling's first version had only a validation:
class Booking < ApplicationRecord
validates :starts_at, uniqueness: {
scope: :mechanic_id,
conditions: -> { where(cancelled_at: nil) }
}
end
Here is what happens with only that line, step by step:
- Request A runs the validation:
SELECT 1 FROM bookings WHERE mechanic_id = 7 AND starts_at = '2024-02-17 09:00' AND cancelled_at IS NULL LIMIT 1. No row. Valid. - Request B runs the same query a few milliseconds later. Request A has not inserted yet. No row. Valid.
- Request A inserts its booking.
- Request B inserts its booking.
- Darragh now has two bikes arriving at 9am, and one customer is going to be disappointed at the counter.
With the partial unique index from the migration, step 4 fails inside the database. Rails raises ActiveRecord::RecordNotUnique. The controller catches it and treats it exactly like the validation failure:
# app/controllers/bookings_controller.rb
def create
@booking = Booking.new(booking_params)
if @booking.save
redirect_to @booking, notice: "Booked. See you on Saturday."
else
render :new, status: :unprocessable_entity
end
rescue ActiveRecord::RecordNotUnique
# The twin got there first. Same message as the validation.
@booking.errors.add(:starts_at, "was just taken. Please pick another time.")
render :new, status: :unprocessable_entity
end
The validation still earns its place: in the common case, where the slot was taken minutes ago, the customer sees the message without the database raising anything. The index handles the rare case the validation cannot. That is "both", and it is why.
If Freewheel ever moves from fixed slots to bookings of different lengths, a unique index on the start time is no longer enough, because a 10am booking can overlap a 9am one that runs 90 minutes. PostgreSQL has an answer, an exclusion constraint, and Rails 7.1 supports it in migrations7. Comparing an integer column with = inside it needs the btree_gist extension13. In a migration it reads:
enable_extension "btree_gist"
add_exclusion_constraint :bookings,
"mechanic_id WITH =, tsrange(starts_at, ends_at) WITH &&",
using: :gist, name: "bookings_no_overlap"
The && operator means "overlaps". Read aloud, the constraint says: no two rows may have the same mechanic and overlapping times.
Callbacks: useful, and the easiest way to hide a side effect
A callback is a method Rails runs at a point in a record's life: before validation, after save, after commit and so on12. They are convenient, which is exactly the danger. A callback runs every time, from every place that saves the record, whether the person writing that code remembers it or not.
The Callbacks guide gives two warnings worth reading twice. Avoid calling update or save inside a callback. And after_save runs inside the database transaction, so if anything later fails, the save is rolled back, but whatever your callback did to the outside world is not12. Only after_commit runs once the data is really stored.
My rule: a callback may tidy its own row. It may not talk to the world. Lowercasing an email, filling in a default, recalculating a total on the same record: fine. Sending email or SMS, calling a payment provider, writing to another system: not in a callback. Put it in the code that makes the business decision, usually a controller action or a small object it calls, and send it through a background job. The chapter on background jobs, email and files later in this series covers that part.
Example: "your bike is ready"
Cian's first idea for the "your bike is ready" text message was this:
# Do not do this
class JobCard < ApplicationRecord
after_save :notify_customer, if: -> { saved_change_to_status?(to: "ready") }
private
def notify_customer
SmsGateway.deliver(bike.customer.phone, "Your bike is ready to collect.")
end
end
Three things go wrong. A manager fixing a typo in the console with card.update!(status: "ready") texts a customer by accident. A data import that marks 200 old cards as ready texts 200 customers. And if the save is part of a larger transaction that rolls back, the customer is told the bike is ready when the database says it is not.
The better shape keeps the decision visible where it happens:
# app/controllers/job_cards_controller.rb
def mark_ready
job_card = JobCard.find(params[:id])
job_card.ready! # enum method: UPDATE status
BikeReadyNotificationJob.perform_later(job_card) # after the update succeeded
redirect_to workshop_board_path(job_card.workshop)
end
Anyone reading mark_ready can see that a text is sent. Nobody reading update! in the console triggers one by accident.
Scopes and enums: names for the questions you ask often
A scope is a named query on a model: scope :on_board, -> { where(status: %i[waiting in_repair ready]) }. You call it like a class method, JobCard.on_board, and you can chain it with other scopes and conditions14. Scopes give the domain a vocabulary. Six months later, "on the board" in the code means exactly what the workshop means by it.
An enum maps a column to a fixed list of named values. Declaring one gives you scopes (JobCard.ready), questions (card.ready?) and bang methods that update (card.ready!)14. By default the values are stored as integers in the order you list them, and the API documentation warns that you must then never reorder the list, only append to it15.
My view: map enums explicitly to strings. The database then contains "in_repair", which a report, an accountant's export or a future system can read without the Ruby file. The API docs note string columns may make queries slower15. For a table of Freewheel's size that cost is invisible, and the index on the column covers the queries that matter. Rails 7.1 also added validate: true, so an unknown value becomes a validation error instead of an ArgumentError115.
Example: the job card status
class JobCard < ApplicationRecord
enum :status, {
waiting: "waiting",
in_repair: "in_repair",
ready: "ready",
collected: "collected"
}, default: :waiting, validate: true
scope :on_board, -> { where(status: %i[waiting in_repair ready]) }
scope :for_workshop, ->(workshop) { where(workshop: workshop) }
end
And in use:
card = JobCard.new(status: "lost")
card.valid? # => false, "Status is not included in the list"
JobCard.for_workshop(limerick_city).on_board.count
# SELECT COUNT(*) FROM "job_cards"
# WHERE "job_cards"."workshop_id" = $1
# AND "job_cards"."status" IN ($2, $3, $4)
The check constraint in the migration, status IN ('waiting', 'in_repair', 'ready', 'collected'), is the database half of the same rule. The enum is for people and code. The constraint is for the shortcut.
Transactions and locks: keep related changes together
A transaction groups several database statements so that either all of them happen or none do. The API documentation's classic example is a bank transfer: money leaves one account only if it arrives in the other16. Every save and destroy already runs in its own transaction. You open one yourself when a single business action writes several rows.
A lock stops two requests from working on the same row at the same time. record.lock! issues SELECT ... FOR UPDATE, and the second request waits until the first transaction ends17. You need one whenever you read a value, compute a new one in Ruby and write it back, because the twin can read the same old value in between.
Example: using a part on a job card
When a mechanic fits a new chain, two things must happen together: the stock goes down and a part usage is recorded. If either fails, neither should stick.
class JobCard < ApplicationRecord
def use_part!(part, quantity:)
transaction do
part.lock! # SELECT ... FOR UPDATE: a second mechanic waits here
part.update!(stock_on_hand: part.stock_on_hand - quantity)
part_usages.create!(part: part, quantity: quantity)
end
end
end
Walk through two mechanics in different bays each fitting the last chain in stock, at the same moment:
- Mechanic A's request locks the chain's row and reads
stock_on_hand = 1. - Mechanic B's request tries to lock the same row and waits.
- A writes
stock_on_hand = 0, records the usage, and the transaction commits. - B's lock is granted and
lock!reloads the row:stock_on_hand = 0. - B tries to write
-1. The model validationgreater_than_or_equal_to: 0fails,update!raises, the transaction rolls back, and no usage is recorded for B.
Without the lock, both would read 1, both would write 0, and the shop would think it had used one chain while two were fitted. The check constraint stock_on_hand >= 0 is the last line: even a script that skips the model cannot drive stock below zero.
One warning from the API documentation is worth knowing early: do not rescue ActiveRecord::StatementInvalid inside a transaction and carry on. On PostgreSQL the transaction is unusable after a database error until it is rolled back16. Rescue outside the transaction block, as the bookings controller above does.
The N+1 problem: 61 queries for one board
The workshop board is the screen on the wall of each workshop. It shows every open job card: the bike, the mechanic, and how many parts have gone into it. It deliberately shows no customer names, because anyone standing at the counter can read it.
At a typical moment a workshop has about 20 open cards. That figure is derived from the example: 1,150 bookings a week across six workshops is about 192 per workshop, or about 32 per working day over six days, and a card stays on the board from drop off to collection.
Cian's first version of the board was perfectly ordinary Rails:
# app/controllers/boards_controller.rb
class BoardsController < ApplicationController
def show
@workshop = Workshop.find(params[:workshop_id])
@job_cards = JobCard.for_workshop(@workshop).on_board.order(:created_at)
end
end
<%# app/views/boards/show.html.erb %>
<% @job_cards.each do |card| %>
<article class="job-card job-card--<%= card.status %>">
<h3><%= card.bike.make %> <%= card.bike.model %></h3>
<p>Mechanic: <%= card.mechanic.name %></p>
<p>Parts fitted: <%= card.part_usages.count %></p>
</article>
<% end %>
It worked grand. It was also slow, and the development log said why. Here it is, abridged:
Started GET "/workshops/3/board" for 127.0.0.1 at 2024-02-13 09:15:02 +0000
Processing by BoardsController#show as HTML
Workshop Load (0.3ms) SELECT "workshops".* FROM "workshops" WHERE "workshops"."id" = $1 LIMIT $2 [["id", 3], ["LIMIT", 1]]
JobCard Load (0.8ms) SELECT "job_cards".* FROM "job_cards" WHERE "job_cards"."workshop_id" = $1 AND "job_cards"."status" IN ($2, $3, $4) ORDER BY "job_cards"."created_at" ASC
Bike Load (0.3ms) SELECT "bikes".* FROM "bikes" WHERE "bikes"."id" = $1 LIMIT $2 [["id", 4120], ["LIMIT", 1]]
Mechanic Load (0.2ms) SELECT "mechanics".* FROM "mechanics" WHERE "mechanics"."id" = $1 LIMIT $2 [["id", 17], ["LIMIT", 1]]
PartUsage Count (0.4ms) SELECT COUNT(*) FROM "part_usages" WHERE "part_usages"."job_card_id" = $1 [["job_card_id", 88231]]
Bike Load (0.3ms) SELECT "bikes".* FROM "bikes" WHERE "bikes"."id" = $1 LIMIT $2 [["id", 3988], ["LIMIT", 1]]
Mechanic Load (0.2ms) SELECT "mechanics".* FROM "mechanics" WHERE "mechanics"."id" = $1 LIMIT $2 [["id", 19], ["LIMIT", 1]]
PartUsage Count (0.3ms) SELECT COUNT(*) FROM "part_usages" WHERE "part_usages"."job_card_id" = $1 [["job_card_id", 88240]]
... the same three lines for each of the other 18 cards ...
Completed 200 OK in 412ms (Views: 318.5ms | ActiveRecord: 41.3ms | Allocations: 182410)
Count the queries that load the cards and what is on them. One query loads the 20 job cards. Then, for every card, one query for its bike, one for its mechanic and one to count its parts. That is 61. (The workshop lookup at the top is one more, and it stays one however many cards there are, so I leave it out of the count.)
This is the N+1 problem, as the Querying guide names it: one query for the list, then one more per row for each association you touch14. Rails loads associations lazily, on first use, which is a good default for a single record and a slow one for a list. Where the same mechanic appears on several cards, the log marks the repeat as CACHE, because Rails caches identical queries within one request. That saves the trip to the database, not the Ruby work around it, and the count still grows with every card.
Example: the arithmetic of the board
Write the number of queries as a function of the number of cards:
Here is the number of queries with lazy loading, is the number of rows on the page and is the number of associations read per row. is the number with eager loading, one query for the list and one per association, and it does not depend on at all. The useful way to read it is at the margin: each extra card costs more queries when loading is lazy and zero when it is eager. Foundations: marginal versus average explains the idea from scratch.
For Cian's board, (bike, mechanic, part count) and :
Two of the three associations, , can be eager loaded. The third, the part count, can be removed entirely with a counter cache. So the fixed page needs:
With eager loaded associations, for any , whether the board shows 20 cards or 40.
On a Saturday, when the board is fuller, the lazy version gets worse with every card. The eager version stays at three. That is what "queries follow the shape of the page, not the size of the data" means.
Example: the fix, step by step
First, eager load the bike and the mechanic, and make the page refuse to lazy load anything:
def show
@workshop = Workshop.find(params[:workshop_id])
@job_cards = JobCard.for_workshop(@workshop).on_board
.includes(:bike, :mechanic) # two extra queries, not forty
.strict_loading # lazy loading now raises
.order(:created_at)
end
Second, use the counter cache. The part_usages_count column and counter_cache: true on PartUsage were set up in the schema. Rails keeps the column up to date as usages are created and destroyed, and answers size from it8. In the view, one word changes:
<p>Parts fitted: <%= card.part_usages.size %></p>
count always asks the database. size uses the counter cache when there is one. That one word is 20 queries.
The log afterwards, again abridged:
Processing by BoardsController#show as HTML
Workshop Load (0.3ms) SELECT "workshops".* FROM "workshops" WHERE "workshops"."id" = $1 LIMIT $2 [["id", 3], ["LIMIT", 1]]
JobCard Load (0.9ms) SELECT "job_cards".* FROM "job_cards" WHERE "job_cards"."workshop_id" = $1 AND "job_cards"."status" IN ($2, $3, $4) ORDER BY "job_cards"."created_at" ASC
Bike Load (0.6ms) SELECT "bikes".* FROM "bikes" WHERE "bikes"."id" IN ($1, $2, $3, ...)
Mechanic Load (0.3ms) SELECT "mechanics".* FROM "mechanics" WHERE "mechanics"."id" IN ($1, $2, $3, $4, $5, $6)
Completed 200 OK in 61ms (Views: 44.2ms | ActiveRecord: 2.1ms | Allocations: 31877)
Three queries for the cards and what is on them. The timings in both logs are illustrative, from a development laptop with seeded data. They show the direction and rough size of the change, not a benchmark.
includes, preload or eager_load
Rails has three ways to load associations in advance, and the Querying guide describes each14:
preloadruns one extra query per association, withWHERE id IN (...), exactly as in the log above.eager_loadruns a single query with a LEFT OUTER JOIN across the tables.includeslets Rails choose. It preloads by default and switches to a join when your conditions refer to the associated table.
A join repeats each parent row once per child row. Load 20 job cards with all their part usages through eager_load and the database sends back one row per usage, with the whole job card copied into each. That is why a has_many with many children usually wants preload.
strict_loading: make the next N+1 fail loudly
strict_loading on a relation makes any lazy load of an association on those records raise an error14. The configuration setting config.active_record.action_on_strict_loading_violation decides whether a violation raises, the default, or is only logged, and strict_loading_by_default can switch it on for every model9.
My view: put strict_loading on the relations behind list pages, explicitly, as in the controller above. It documents the page's loading plan in the code, and the day someone adds card.bike.customer.name to the board, their development page raises instead of quietly adding 20 queries. Switching it on for the whole application at once is a bigger change for an existing codebase. For a new one, it is worth considering from the first model.
Example: the two row test
A rule is only as good as the check that enforces it. This integration test pins the board's query count. It loads the board with two cards, then with 20, and fails if the number of queries changed:
# test/integration/board_query_budget_test.rb
require "test_helper"
class BoardQueryBudgetTest < ActionDispatch::IntegrationTest
test "the board's query count does not grow with the number of cards" do
workshop = workshops(:limerick_city) # fixtures hold two open cards
with_two = queries_during { get workshop_board_path(workshop) }
18.times do
JobCard.create!(workshop: workshop, bike: bikes(:commuter), mechanic: mechanics(:darragh))
end
with_twenty = queries_during { get workshop_board_path(workshop) }
assert_equal with_two, with_twenty
end
private
# Counts the SQL statements Active Record sends while the block runs
def queries_during(&block)
count = 0
counter = ->(_name, _start, _finish, _id, payload) do
count += 1 unless %w[SCHEMA TRANSACTION].include?(payload[:name])
end
ActiveSupport::Notifications.subscribed(counter, "sql.active_record", &block)
count
end
end
It listens to sql.active_record, the event Active Record publishes for every statement, with the statement's name in the payload18. Run against Cian's first version, it fails with 8 queries against 62: the workshop lookup, the cards, and three per card. Against the fixed version it passes with 4 and 4: the workshop, the cards, the bikes and the mechanics. I write tests like this first, before the fix, because watching it fail is the proof that it can catch the problem. The testing series later in the programme goes into that habit properly.
Indexes and EXPLAIN: ask the database how it will answer
An index is a separate, sorted structure the database keeps so it can find rows without reading the whole table, much like the index at the back of a book. Foreign key columns created with t.references get one automatically. Columns you filter on together often deserve one together.
EXPLAIN asks PostgreSQL how it plans to run a query, and EXPLAIN ANALYZE actually runs it and reports the real time and row counts19. Rails 7.1 lets you pass these options straight from a relation, so you never have to copy SQL into a terminal14.
There is one trap for beginners. On a small table, PostgreSQL often ignores your index and reads the whole table, because that is genuinely faster for a few hundred rows. An EXPLAIN on your development database can tell you nothing about production. Run it against realistic volumes.
Example: the board query two years in
At about 1,150 bookings a week, job_cards grows by roughly 60,000 rows a year, so after two years it holds around 120,000, about 20,000 per workshop. Those are derived figures, not measured ones. Here is the board's query at that size, with only the automatic index on workshop_id:
JobCard.for_workshop(workshop).on_board.order(:created_at).explain(:analyze)
EXPLAIN (ANALYZE) SELECT "job_cards".* FROM "job_cards" WHERE ...
Sort (actual time=21.402..21.405 rows=20 loops=1)
-> Bitmap Heap Scan on job_cards (actual time=1.210..21.370 rows=20 loops=1)
Recheck Cond: (workshop_id = 3)
Filter: ((status)::text = ANY ('{waiting,in_repair,ready}'::text[]))
Rows Removed by Filter: 19980
-> Bitmap Index Scan on index_job_cards_on_workshop_id
Execution Time: 21.470 ms
The plan output is abridged and illustrative. Read it from the inside out. PostgreSQL used the workshop_id index to find all 20,000 cards of the workshop, then read each one and threw away 19,980 because their status was collected. The line to look for is "Rows Removed by Filter": a large number there means the index got the database to the right neighbourhood, but not to the right door.
The fix is an index that matches the question, workshop and status together:
class AddBoardIndexToJobCards < ActiveRecord::Migration[7.1]
def change
add_index :job_cards, [:workshop_id, :status]
end
end
Sort (actual time=0.112..0.115 rows=20 loops=1)
-> Index Scan using index_job_cards_on_workshop_id_and_status on job_cards (actual time=0.031..0.089 rows=20 loops=1)
Index Cond: ((workshop_id = 3) AND ((status)::text = ANY ('{waiting,in_repair,ready}'::text[])))
Execution Time: 0.160 ms
Twenty rows read, twenty rows returned. A multicolumn index can also serve queries on its first column alone, as the PostgreSQL documentation explains20, so the single column index on workshop_id is now redundant and can be dropped in a later migration.
Batches: do not load 9,000 customers at once
Customer.all.each loads every customer into memory as Ruby objects before the loop starts. For 9,000 rows that is merely wasteful, and you would get away with it. For the tables Freewheel will have in a few years, it can exhaust the server's memory. The Querying guide's answer is find_each, which fetches records in batches of 1,000 by default and hands them to your block one at a time14.
The guide adds a sensible caveat: for a loop over a thousand records or so, plain finders are fine. Batches are for work that would not fit comfortably in memory.
Two more habits belong here. First, if the work can be done in SQL, do it in SQL: a nightly reorder report is a query, not a loop. Second, a loop that changes data is a migration of a kind, so it should be repeatable and report what it skipped.
Example: the nightly reorder report and a one off clean up
The reorder report asks one question of 2,400 parts, and the database answers it in one query:
class Part < ApplicationRecord
scope :to_reorder, -> { where("stock_on_hand <= reorder_level").order(:sku) }
end
Part.to_reorder.pluck(:sku, :name, :stock_on_hand)
# SELECT "parts"."sku", "parts"."name", "parts"."stock_on_hand" FROM "parts"
# WHERE (stock_on_hand <= reorder_level) ORDER BY "parts"."sku" ASC
The clean up is different. The old spreadsheets stored emails as typed: "Niamh@Example.com ", "niamh@example.com". After adding normalizes to Customer (next section), every existing row needs tidying once. That is a loop:
# lib/tasks/customers.rake
namespace :customers do
desc "Normalise stored emails and phone numbers once"
task normalise: :environment do
Customer.find_each do |customer| # 9 batches of 1,000
customer.normalize_attribute(:email)
customer.normalize_attribute(:phone)
next unless customer.changed?
customer.save!
rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique => e
# Two spellings of one email: a duplicate customer to merge by hand
puts "Customer #{customer.id}: #{e.message}"
end
end
end
bin/rails customers:normalise runs nine queries of 1,000 rows each instead of one of 9,000, and any duplicate it uncovers is reported instead of crashing the run. The unique index on customers.email is what makes the duplicate visible. Without it, the normalised spreadsheet import would have quietly given Niamh two customer records.
Money and time zones: two columns that punish shortcuts
Money: whole cent, never floats
A float is a binary approximation of a decimal number. Ruby's documentation calls floating point "an inexact number"21, and you can see it in one line:
0.1 + 0.2 # => 0.30000000000000004
For money that is unacceptable. Store whole cent in an integer column, as price_cents does above, or use a decimal column with a fixed scale, which Rails maps to Ruby's exact BigDecimal. Both are sound. I prefer integers for their simplicity: sums are exact, and nobody can accidentally create a float. The choice itself was covered in the first decisions for a new Rails application.
Example: an average repair in cent
A typical Freewheel repair takes 90 minutes at the labour rate of €52 an hour, plus a chain and a brake cable at €17 together:
labour_rate_cents = 5_200 # €52.00 an hour
labour_cents = labour_rate_cents * 90 / 60 # => 7800, exact
parts_cents = 1_700
total_cents = labour_cents + parts_cents # => 9500, that is €95.00
ActiveSupport::NumberHelper.number_to_currency(total_cents / 100.0, unit: "€")
# => "€95.00", for display only
The division by 100 happens once, at the very edge, in the view. Everything before it is whole numbers.
Time zones: store UTC, think local
Rails stores times in the database in UTC and converts them to the application's zone when it reads them9. You set that zone once:
# config/application.rb
config.time_zone = "Dublin"
Then use Time.current and Time.zone.local, never Time.now, which uses the server's zone22. Rails converts your local times to UTC in the SQL for you.
The trap is SQL you write yourself. PostgreSQL knows nothing about config.time_zone. A query that groups by DATE(created_at) groups by the UTC date, and in Irish summer time a booking made at half past midnight on Saturday is stored as 11.30pm on Friday.
Example: measuring the Saturday peak correctly
Niamh wants to know whether 30% of online bookings really arrive between Friday 6pm and Saturday noon. The arrival time is created_at. In Ruby, Rails handles the zones:
friday_6pm = Time.zone.local(2024, 2, 16, 18, 0) # 6pm in Limerick (18:00 UTC in winter, 17:00 UTC in summer)
peak = Booking.where(created_at: friday_6pm...(friday_6pm + 18.hours)).count
week = Booking.where(created_at: friday_6pm.beginning_of_week...friday_6pm.end_of_week).count
share = peak.fdiv(week) # => 0.3 if the pattern holds
For a report grouped by day in SQL, convert explicitly before taking the date:
Booking.group(
Arel.sql("DATE(created_at AT TIME ZONE 'UTC' AT TIME ZONE 'Europe/Dublin')")
).count
The first AT TIME ZONE 'UTC' tells PostgreSQL the stored value is UTC. The second converts it to local time in Limerick. Only then is the date the date Niamh means.
What Rails 7.1 added to Active Record
Rails 7.1 was released on 5 October 20232. Five of its additions matter for modelling, and the release notes describe each1.
normalizes
normalizes declares how an attribute is cleaned whenever it is assigned, and it also applies to finder arguments, so Customer.find_by(email: " Niamh@Example.com") finds the stored lowercase address. It replaces the before_validation callbacks many applications used for the same job, which also makes it the cleanest illustration of "a callback may tidy its own row".
Example: customer email and phone
class Customer < ApplicationRecord
has_many :bikes, dependent: :destroy
has_many :bookings, dependent: :restrict_with_error
normalizes :email, with: ->(email) { email.strip.downcase }
normalizes :phone, with: ->(phone) { phone.delete("^0-9+") } # keep digits and +
validates :name, presence: true
validates :email, presence: true, uniqueness: true
end
Existing rows are not touched until you call normalize_attribute on them and save, which is exactly what the rake task above does23.
generates_token_for
generates_token_for creates signed, tamper proof tokens for a purpose, with an optional expiry. A block can embed a value from the record, and if that value has changed by the time the token comes back, the token is treated as invalid24.
Example: the "manage your booking" link
Freewheel's confirmation email carries a link to move or cancel the booking without logging in:
class Booking < ApplicationRecord
generates_token_for :manage, expires_in: 14.days do
starts_at # once the slot changes, older links stop working
end
end
token = booking.generate_token_for(:manage) # goes into the email link
Booking.find_by_token_for(:manage, token) # => the booking, or nil
No token column, no clean up job for expired tokens. If the customer moves the booking, every older link dies by itself, because the embedded start time no longer matches.
authenticate_by
For models with has_secure_password, authenticate_by(email:, password:) finds the record and checks the password in one call. It digests the password even when no record matches, which protects against timing attacks that reveal whether an account exists25. Freewheel's managers will log in with it. The chapter on authentication, authorisation and security later in this series builds that properly.
Composite primary keys
Rails 7.1 supports primary keys made of more than one column, declared with create_table :part_usages, primary_key: [:job_card_id, :part_id]18. The release notes point out that this suits many to many tables.
My view, as of now: for a new application, keep the ordinary id column and add a unique index on the pair, as the Freewheel migration does. Rails routes, forms and many gems are built around a single id, and a feature this new has had little time in the wild. Composite keys come into their own when you inherit a database designed that way, and there they are a real improvement.
Async queries
Rails 7.0 added load_async. Rails 7.1 adds asynchronous versions of the aggregate methods: async_count, async_sum, async_pluck and more1. Each returns a promise, and the query runs on a background thread while your code carries on.
Example: the manager's dashboard
def dashboard
week = Time.current.all_week
bookings = Booking.where(starts_at: week, cancelled_at: nil).async_count
open = JobCard.on_board.async_count
low_stock = Part.to_reorder.async_count
@stats = { bookings: bookings.value, open_cards: open.value, low_stock: low_stock.value }
end
Three independent counts run at the same time instead of one after another. One configuration step is easy to miss: config.active_record.async_query_executor defaults to nil, which runs these queries in the foreground as if they were not asynchronous at all. Set it to :global_thread_pool for a single database, and make the connection pool large enough for the extra threads9.
For the person paying for this
You do not need to read Ruby to check that your data is in good hands. Ask your developer these questions, and expect short, specific answers.
| Question | A good answer sounds like |
|---|---|
| Which rules does the database itself enforce? | "Every required field is NOT NULL, every link is a foreign key, and double bookings are blocked by a unique index." |
| What stops two people booking the same slot? | A named constraint or index, not "the form checks it". |
| How is money stored? | "Whole cent in integer columns" or "decimal with two places". Never "float". |
| How many queries do the three busiest pages run? | A number for each, and a test that fails if it grows with the data. |
| Is the schema file in version control? | "Yes, schema.rb (or structure.sql), and every change goes through a migration." |
| What happens when a status changes? | Side effects such as emails and texts are sent from one visible place, not from hidden callbacks. |
None of this costs extra time when it is done from the first migration. All of it costs real time when it is retrofitted onto 120,000 rows. If you are commissioning a Rails application and want this level of care in the data model, that is the work I do on web application development.
How this compares with Django
The Django ORM covers the same ground with different defaults, and a senior Django developer would recognise every problem in this chapter. The real differences are in the workflow. Django models declare their fields, and makemigrations writes the migration from them5, where Rails asks you to write the migration and reads the columns back. Django calls the N+1 fix select_related and prefetch_related, which line up closely with eager_load and preload. And Django, like Rails, puts the double booking question to the database: a uniqueness check in a form cannot see the twin either.
The Django series builds this exact schema, with the same 61 query board, in its chapter on the Django ORM. Reading both is the fairest way to compare the frameworks on the thing that matters most, the data. If you are still choosing between them, how to choose between Django and Rails sets out a method, and Django and Rails in production shows why query counts matter more than framework speed.
Conclusion
Active Record makes the database feel like Ruby, which is its gift and its risk. The gift is speed: the Freewheel schema, eight tables with real rules, fits in a few short migrations and models. The risk is that SQL you do not see is SQL you do not count, and a rule you only check in Ruby is a rule the shortcut and the twin will break.
So write migrations by hand with NOT NULL, foreign keys, unique indexes and check constraints, and keep the validations for the people using the forms. Keep callbacks to tidying their own row. Name your enums with strings and your common questions with scopes. Wrap related writes in a transaction and lock what you read before you write. Load lists with includes or preload, guard them with strict_loading, and pin their query count with the two row test. Store money as whole cent, store times in UTC, and let EXPLAIN tell you which index the database actually wants.
If you would like a second pair of eyes on a data model before it fills up, book the free workshop. We go through your schema together, and the first two weeks of work are on me.
