Home · ELI5

Ruby on Rails · ActiveRecord::Relation

How Rails loads books

A relation keeps a request for records and can hold the records it loads.

Illustrative Book example · synchronous, plain Rails 8.1.3 relation

1. Choose the books

Calling where builds a relation with a rule for which books to fetch.

Database rows · illustrative

Asterfiction · id 1
Beaconhistory · id 2
Cloudfiction · id 3

Current request · relation

books = Book.where(category: "fiction").order(:title)

Predict which books will load, then read the same request twice.

loaded? falseFetches in this demo: 0

Records held by this relation

Records have not loaded.

Request built; records not loaded.

What this playground models
  • The page uses an in-memory teaching model; it runs no Rails code or SQL.
  • Each category change builds a fresh, unloaded request, sorted by title.
  • It leaves out adapters, the SQL query cache, console inspection, async loading, and associations.
  • Other calls, such as count, can query the database without loading these Book objects.

2. Chain another rule

Adding order(:title) returns a new relation with the sort rule while keeping the original request unchanged.

Original relation

fiction = Book.where(category: "fiction")

Rule: fiction

order(:title)

New relation

books = fiction.order(:title)

Rules: fiction + title order

Both requests are unloaded in this example.

Why chaining works
  • These query methods return relations, so you can add more query rules.
  • The new relation starts unloaded even when the original relation is loaded.

3. Read the records

On this unloaded relation, to_a fetches the matching rows and returns an array of Book objects.

Request

books.to_a

Fiction · title order

Fetch rows

Array of Book objects

AsterBook · id 1
CloudBook · id 3

The relation now holds these records · loaded? true

Other ways to load
  • books.each { |book| ... } also loads this relation before reading each record.
  • books.load loads the records and returns the relation itself.
  • to_a returns a copy of the records array; the Book objects are shared.

4. Read them again

Another to_a or each on the same loaded relation reuses the records it holds.

Same relation · stored records

AsterBook · id 1
CloudBook · id 3
books.to_a

Second read

Aster · Cloud

Uses stored Book objects

One fetch across both reads in this example

When stored records get stale
  • Later database changes do not refresh these records automatically.
  • books.reload clears the stored records and fetches them again.
  • A fresh relation has its own loading state.