skip to content

In Active Record, which queries does Order.includes(:customer, line_items: :wine) run for an orders page printing customers, items and wines?

level: juniorimportance: must knowfreq 82%

answer

  1. one query per association, not per row
  2. IN list built from collected ids
  3. hash syntax for the nested level
  4. set on the relation before it loads
  5. four statements for this page

basics

~20 s

With no conditions on the associations, it runs four queries in total: one for the orders, then one IN-list query each for customers, line items and wines, so order.customer and line_item.wine read from memory instead of querying per row.

solid answer

~40 s

`includes` only records association names on the relation. When the relation loads, Active Record runs `SELECT orders.*`, collects the `customer_id` values and runs one `customers` query with `WHERE id IN (...)`, collects the order ids for one `line_items` query on `order_id IN (...)`, then collects the line items' `wine_id` values for one `wines` query. The records are attached to each order's association, so the view's `order.customer.name` and `item.wine.name` hit memory. The hash form `line_items: :wine` is how you name a nested level; arrays and deeper hashes combine freely. The call belongs on the relation the controller builds, before anything iterates it, and anything the view reads that you did not list (say `customer.default_address`) still loads lazily, once per record.

code

ruby · 6 lines
ruby
class Admin::OrdersController < ApplicationController
  def index
    @orders = Order.includes(:customer, line_items: :wine)
                   .order(created_at: :desc)
  end
end

go deeper

for a junior

Recall that includes takes association names, that a hash names a nested level, and that it removes the per-row queries by loading each association in one query.

for a middle

Explain the IN-list queries step by step, why the statement count follows the number of associations rather than rows, and why where or order on a loaded association queries again.

for a senior

Show you pick the loader deliberately: separate queries by default, a join only when a condition needs one, and only the associations the page actually reads.

for a principal

Frame eager loading as a page-level contract: each screen names its data up front, and tooling enforces that no view quietly adds a lazy load later.

## The page and the relation behind it A wine-shop admin has an **orders page**: for each `Order` it prints the customer's name, then every line item with its wine. The models are ordinary: `Order belongs_to :customer` and `has_many :line_items`, and `LineItem belongs_to :wine`. Without help, Active Record loads each association **lazily**, the first time the view touches it, so the page issues one `customers` query per order, one `line_items` query per order and one `wines` query per line item. `includes` is the everyday fix. It is a **relation method**: it stores association names on the `ActiveRecord::Relation` and does nothing until the relation is loaded. ```ruby @orders = Order.includes(:customer, line_items: :wine).order(created_at: :desc) ``` ## What runs when the relation loads With no condition that mentions an associated table, `includes` behaves exactly like `preload` and runs **separate queries**, one per association: 1. `SELECT "orders".* FROM "orders" ORDER BY ...` loads the orders. 2. `SELECT "customers".* FROM "customers" WHERE "customers"."id" IN (...)` uses the `customer_id` values collected from step 1. 3. `SELECT "line_items".* FROM "line_items" WHERE "line_items"."order_id" IN (...)` uses the order ids. 4. `SELECT "wines".* FROM "wines" WHERE "wines"."id" IN (...)` uses the `wine_id` values from step 3's rows. That is **four statements for this page**, whether it lists ten orders or two hundred; the count grows with the number of associations named, not with the number of rows. Each loaded record is attached to its owner's association, which is then marked loaded, so `order.customer` and `item.wine` return objects already in memory. ## The argument syntax The argument mirrors the association graph: - a **symbol** names one association on the model: `includes(:customer)`; - several arguments or an **array** name siblings: `includes(:customer, :line_items)`; - a **hash** steps one level down: `includes(line_items: :wine)` loads line items and then each item's wine; - hashes and arrays **nest**: `includes(customer: :default_address, line_items: [:wine, :discount])`. Every key must be an association on the model at that level. `includes(:line_items, :wine)` fails because `Order` has no `wine` association, and Active Record raises `ActiveRecord::AssociationNotFoundError` when it tries to load it. ## Where the call belongs - **On the relation, before it loads.** Put it in the controller action (or a named scope the action calls). Once `@orders` has been iterated, chaining `includes` builds a new relation; it does not reach back into records already loaded. - **Name every level the view reads.** If the template also prints `order.customer.default_address.city`, that third level loads lazily for each customer unless the hash names it. - **Do not re-query a loaded association.** `order.line_items.where(...)` or `order.line_items.order(:position)` builds a fresh query per order and ignores what `includes` loaded. Filter or sort the loaded array in Ruby (`select`, `sort_by`) or preload a differently scoped association. - **Load only what the page reads.** Every extra name adds a query and objects held in memory, which is why detectors also flag unused eager loads. ## What includes leaves unchanged `includes` changes **how** associated records arrive, not **which** orders come back: - The orders, their sort and their count are the same as without it; without a condition on an associated table there is no join to add or remove rows. - A `limit(25)` on the relation limits orders only. The line-items query then loads **every** item of those 25 orders, however many that is. - Each association is loaded **whole**. If a page only needs the newest three line items per order, `includes` still loads all of them; that is a separate design problem, not something the loader trims. - Chaining order does not matter before the load: `Order.includes(:customer).where(status: :paid)` and `Order.where(status: :paid).includes(:customer)` build the same relation. ## Mistakes interviewers listen for | Belief | What Active Record actually does | |---|---| | `joins(:customer)` loads the customers | It adds an INNER JOIN for filtering; `order.customer` still queries per order | | `includes` always runs one big JOIN | It runs separate IN queries unless a condition or `references` forces a JOIN | | Rails batches lazy loads in a loop on its own | Each lazy load on a separate record runs its own query | | `includes(:wine)` on orders reaches the items' wines | Nested levels need the hash form, `line_items: :wine` | The interview answer is the four statements, why the count no longer depends on the number of rows, and the hash syntax for a nested level.

  • The template also prints order.customer.default_address.city. What changes?
    That is a third level the relation never named, so each customer loads its address lazily, one query per customer. Extend the hash: `includes(customer: :default_address, line_items: :wine)`. Active Record then adds one more IN query for addresses, keeping the page at a fixed number of statements.
  • Inside the loop the view calls order.line_items.where(gift_wrap: true). Does the includes still help?
    No. Calling `where` on the association builds a new relation and runs a query per order, ignoring the loaded line items. Filter the loaded records in Ruby with `order.line_items.select(&:gift_wrap?)`, or preload a separately scoped association that holds only gift-wrapped items.

Instead of one warehouse trip per order slip to fetch that order's bottles, the clerk reads every slip first and fetches all the bottles in one trip per shelf: one for customers, one for line items, one for wines.

  • Order.joins(:customer) loads the customers so order.customer stops querying
  • includes always produces a single query with a JOIN
  • Rails batches the lazy loads inside a loop automatically
  • includes(:line_items, :wine) loads each line item's wine
  • Adding includes after the records are loaded fixes the loop