skip to content

When rolling out Active Record's strict_loading across an existing Rails 8.1 app, which levels, modes and violation actions would you use, and in what order?

level: seniorimportance: should knowfreq 34%

answer

  1. relation, record, association, model, app
  2. StrictLoadingViolationError under :raise
  3. :log publishes a notification, debug-level line
  4. :n_plus_one_only trips on has_many children
  5. strict_loading: false exempts one association

basics

~20 s

Start with .strict_loading on list relations, then go app-wide in development and test with the default :raise, and run production on :log with a notification subscriber so a missed load is reported instead of raising.

solid answer

~40 s

`strict_loading` makes a lazy association load fail instead of silently querying. It exists at five levels: a relation (`Order.strict_loading`), a record (`order.strict_loading!`), an association (`has_many :line_items, strict_loading: true`), a model (`self.strict_loading_by_default = true`) and the app (`config.active_record.strict_loading_by_default`). The default action is `:raise` (`ActiveRecord::StrictLoadingViolationError`); `config.active_record.action_on_strict_loading_violation = :log` publishes a `strict_loading_violation.active_record` notification instead, which Active Record's log subscriber writes only at debug level, so a production app logging at info needs its own subscriber. The `:n_plus_one_only` mode lets a record lazy-load its own associations but marks records it loads through a `has_many` strict, so a per-child lazy load raises. A sane order: hot list actions with `.strict_loading` first, then models, development and test with `:raise`, production on `:log` until the violation feed is quiet.

code

ruby · 18 lines
ruby
# config/environments/test.rb
config.active_record.strict_loading_by_default = true

# config/environments/production.rb
config.active_record.strict_loading_by_default = true
config.active_record.action_on_strict_loading_violation = :log

# config/initializers/strict_loading.rb
ActiveSupport::Notifications.subscribe("strict_loading_violation.active_record") do |event|
  owner = event.payload[:owner]
  reflection = event.payload[:reflection]
  Rails.logger.warn("strict_loading: #{owner.name}##{reflection.name}")
end

# app/models/order.rb
class Order < ApplicationRecord
  has_many :tasting_notes, strict_loading: false
end

go deeper

for a junior

Recall that strict loading raises ActiveRecord::StrictLoadingViolationError when an association loads lazily, and that includes or preload avoids it.

for a middle

Explain the five levels, how an association's strict_loading option overrides its owner, and what the :n_plus_one_only mode allows.

for a senior

Plan the rollout: raise in development and test, log with a subscriber in production, relation-level strictness on list pages, deliberate exemptions.

for a principal

Weigh strictness against delivery speed: decide which teams and models go strict first and how violation data drives that schedule.

## What strict loading does **Strict loading** turns a lazy association load into a reported violation. Instead of `order.customer` quietly running `SELECT ... FROM customers`, Active Record calls its violation handler before the query. Under the default action, `:raise`, that handler raises `ActiveRecord::StrictLoadingViolationError` with a message naming the model and the association. Associations loaded up front with `includes`, `preload` or `eager_load` are already in memory, so they never trip it, and a strict relation passes its strictness on to the records it preloads or eager loads. Strict loading is switched off while a record runs its validations, so an association validation can still load what it needs. ## The five places to switch it on | Level | How | Scope | |---|---|---| | Relation | `Order.strict_loading.includes(:customer)` | Records from this relation, and records it eager loads | | Record | `order.strict_loading!` / `order.strict_loading!(false)` | One instance | | Association | `has_many :line_items, strict_loading: true` | That association, whatever its owner's setting | | Model | `self.strict_loading_by_default = true` in the class | Every instance of that model | | App | `config.active_record.strict_loading_by_default = true` | Every model | An explicit `strict_loading:` option on an association wins over the owner's setting, so `has_many :tasting_notes, strict_loading: false` exempts one association on an otherwise strict model. No `load_defaults` version turns strict loading on: the app default stays `false` in Rails 8.1. ## Modes: :all and :n_plus_one_only The **mode** decides which lazy loads count. `:all`, the default, reports every lazy load on a strict record. `:n_plus_one_only`, set per record with `strict_loading!(mode: :n_plus_one_only)` or app-wide with `config.active_record.strict_loading_mode`, lets the record lazy-load its own associations, but every record it then loads lazily through a `has_many` comes back strict. So on an order show page, `@order.line_items` loads fine and `@order.line_items.first.wine` raises: that is the one-query-per-item pattern. Two consequences matter: - `:n_plus_one_only` is a gentler first step for **single-record pages**, where loading one order's customer lazily costs one query. - It does **not** catch the classic list problem on the records the list query itself returned: with the model in this mode, `Order.all.each { |o| o.customer }` does not raise. A relation-level `.strict_loading` uses `:all` on its records, so list actions should use that. ## Violation actions: :raise and :log `config.active_record.action_on_strict_loading_violation` takes `:raise` (default, all environments) or `:log`. Under `:log`, Active Record publishes a `strict_loading_violation.active_record` event through `ActiveSupport::Notifications`. Its own log subscriber writes that event **at debug level only**, and the generated `production.rb` sets `config.log_level` from `RAILS_LOG_LEVEL` with a default of `"info"`. A production app on `:log` therefore records nothing visible until you subscribe to the event yourself and count or report it. ## Mistakes seen during rollouts | Mistake | What actually happens | |---|---| | Expecting `:log` output in production logs | The line is debug-level; at info nothing appears without a subscriber | | Using model-wide `:n_plus_one_only` to protect index pages | Lazy loads on the list's own records still pass; use `.strict_loading` on the relation | | Exempting with a scope, `-> { strict_loading(false) }` | The owner's check runs before the scope is built; use the `strict_loading: false` option | | Turning on `:raise` in production first | Every unlisted association becomes an error page for users | ## A rollout order that survives production 1. **Start on hot list actions.** Add `.strict_loading` to the relations behind the busiest index pages; each failing test or page names a missing `includes`. 2. **Turn it on in development and test.** Set `strict_loading_by_default = true` in `config/environments/development.rb` and `test.rb` with `:raise`, so new code fails in CI rather than in production. 3. **Run production on `:log` with a subscriber.** Subscribe to `strict_loading_violation.active_record`, group by model and association, and fix the noisiest first. 4. **Exempt on purpose.** Use `strict_loading: false` on an association or `record.strict_loading!(false)` where a lazy load is intended, such as a rarely opened detail panel. 5. **Tighten the mode.** Move models from `:n_plus_one_only` to `:all` once the feed is quiet. The senior answer names the levels, the default action and exception, why `:log` is invisible at info level, and what `:n_plus_one_only` does and does not catch.

  • Order.strict_loading.includes(:line_items) loads fine, but item.wine raises in the view. Why?
    Strict loading cascades to records loaded through the relation's preload or eager load, so each line item is strict too. The wines were never listed, so `item.wine` is a lazy load on a strict record. Name the next level: `includes(line_items: :wine)`.
  • Does strict loading stop order.line_items.count from querying?
    No. Strict loading guards loading an association's records; `count` on an association runs a COUNT through the calculation path without loading the target, so it does not trip the check. It only stops lazy record loads, so pair it with review of per-row aggregate calls.

  • strict_loading only logs a warning by default
  • :log mode writes violations to the production log at info level
  • load_defaults 8.1 turns strict_loading_by_default on
  • :n_plus_one_only catches order.customer on every order in a list
  • A scope with strict_loading(false) on an association exempts it
  • Strict loading stops preloaded associations from being read

Assumes Rails 8.1.4 with load_defaults 8.1: strict loading stays off by default, the violation action defaults to :raise, and the generated production.rb logs at info, below the debug-level violation line.