A Rails page listing fifty freelancers with avatar thumbnails runs hundreds of queries; how do with_attached_avatar and with_all_variant_records fix Active Storage's N+1?
answer
- attachment and blob loaded per row
- variant records loaded per thumbnail
- with_attached_* is an includes scope
- track_variants adds variant records to it
- strict_loading: true on the macro
basics
~20 sEach avatar lazily loads its attachment row, its blob and, for processed variants, its variant record and that record's blob. Freelancer.with_attached_avatar preloads all of them in a fixed number of queries; with_all_variant_records does the same for one record's attachments.
solid answer
~40 s`image_tag freelancer.avatar.variant(:thumb)` needs the `avatar_attachment` and its blob to build the URL, so a loop over fifty freelancers loads them one row at a time. Calling `.processed.url` (or `.processed` anywhere) also looks up the blob's variant record and the variant's own attachment and blob for each image. `has_one_attached` defines a scope, `with_attached_avatar`, that is an `includes` of `avatar_attachment: :blob`; with `track_variants` on (the 8.1 default) it also includes `variant_records: { image_attachment: :blob }` and preview images, so the page runs a fixed set of queries regardless of row count. For the attachments of one already-loaded record, `freelancer.portfolio_images.with_all_variant_records` preloads the same tree. Adding `strict_loading: true` to the macro turns any missed preload into an `ActiveRecord::StrictLoadingViolationError` in development and tests.
code
ruby · 17 linesclass Freelancer < ApplicationRecord
has_one_attached :avatar, strict_loading: true do |attachable|
attachable.variant :thumb, resize_to_fill: [96, 96]
end
has_many_attached :portfolio_images
end
class FreelancersController < ApplicationController
def index
@freelancers = Freelancer.where(available: true).with_attached_avatar.order(:name)
end
def show
@freelancer = Freelancer.find(params.expect(:id))
@images = @freelancer.portfolio_images.with_all_variant_records
end
endgo deeper
Recall that every attachment is extra rows to load and that Model.with_attached_name is the scope that preloads them for a list.
Explain the association chain (attachment, blob, variant record, variant blob), what with_attached_* expands to with track_variants on, and when with_all_variant_records applies.
Diagnose a slow listing from its query log, decide between lazy URLs and processed URLs, and guard the fix with strict_loading: true or a query-count test.
Set the team's convention for where collections are preloaded and how N+1 regressions are caught, weighing strict loading's noise against silent production slowdowns.
## Where the queries come from An attachment is two associations deep: the model `has_one :avatar_attachment`, which `belongs_to :blob`. Variants add two more levels: the blob `has_many :variant_records`, each of which `has_one_attached :image`. In a listing like this: ```erb <% @freelancers.each do |freelancer| %> <%= image_tag freelancer.avatar.variant(:thumb).processed.url %> <% end %> ``` each iteration lazily loads: 1. the freelancer's `avatar_attachment` row; 2. that attachment's `blob`; 3. the blob's variant record matching the `:thumb` variation digest, through `processed`; 4. that variant record's `image_attachment` and its blob, to get the variant's key and URL. Fifty freelancers become a couple of hundred queries. Without `.processed`, a lazy `image_tag freelancer.avatar.variant(:thumb)` still pays steps 1 and 2 per row, because the URL carries the blob's signed id and filename; the variant lookup then happens in each image request instead of the page render. ## with_attached_* is a preloading scope The macro defines **`with_attached_<name>`** on the model. Its body, from `ActiveStorage::Attached::Model`, depends on `ActiveStorage.track_variants`: | `track_variants` | `Freelancer.with_attached_avatar` expands to | |---|---| | `false` | `includes(avatar_attachment: :blob)` | | `true` (default since `load_defaults 6.1`) | `includes(avatar_attachment: { blob: { variant_records: { image_attachment: :blob }, preview_image_attachment: { blob: { variant_records: { image_attachment: :blob } } } } })` | Use it like any scope: `Freelancer.where(available: true).with_attached_avatar.order(:name)`. For `has_many_attached :portfolio_images` the scope is `with_attached_portfolio_images`. Because it is an `includes`, Active Record normally loads each level with a separate `IN (...)` query, so the count grows with the depth of the tree, not with the number of freelancers. ## When the records are already loaded `with_attached_*` works on a relation of owners. When you hold one freelancer and loop over its many attachments, use the scope on `ActiveStorage::Attachment`: ```ruby freelancer.portfolio_images.with_all_variant_records.each do |image| image_tag image.variant(:thumb).processed.url end ``` **`with_all_variant_records`** includes each attachment's blob, its variant records with their image blobs, and the preview-image chain, so the loop no longer queries per image. ## Making the mistake loud Preloading is easy to lose when a partial is reused from a new controller. Two guards: - **`strict_loading: true`** on the macro (`has_one_attached :avatar, strict_loading: true`) marks both generated associations strict. A lazy load then triggers a strict-loading violation, which raises `ActiveRecord::StrictLoadingViolationError` under the default `action_on_strict_loading_violation` of `:raise`, or logs if the app sets it to `:log`. - A query counter in a request or system test, or an N+1 detector in development, catches the regression before production. ## Choosing what to preload and where processing happens - Preload in the controller or query object that builds the collection (`@freelancers = Freelancer.listed.with_attached_avatar`), not in the view. - If thumbnails are **lazy** URLs, the page only needs attachments and blobs; variant-record lookups move to the image requests, one per thumbnail, which the browser makes in parallel. That keeps page render time flat even when some variants are not generated yet. - If the page calls **`.processed.url`**, preload variant records too (the default scope already does with tracking on), and consider `preprocessed: true` so no page render ever waits on libvips. - Turning `track_variants` off removes the variant tables from the picture, but then checking whether a variant exists means asking the storage service, which is slower than a preloaded row. The general mechanics of `includes`, `preload` and `eager_load` and when Active Record switches to a JOIN are the eager-loading topic's; what is specific here is that Active Storage hides two to four association levels behind one method call, and ships the scopes that name them for you.
- Why does with_attached_avatar include preview_image_attachment when avatars are images?The scope is generic: the same macro serves PDFs and videos, whose previews are stored as a `preview_image` attachment on the blob with their own variant records. The scope includes that chain so `representation` and `preview` calls also avoid per-row queries; for pure images that level simply returns no rows.
- Does preloading with with_attached_avatar download any image bytes?No. It loads database rows only: attachments, blobs and variant records. The bytes stay in the storage service until a browser requests a URL or code calls `download` or `open` on a blob.
- Active Storage batches attachment lookups automatically, so loops never cause N+1
- with_attached_avatar loads the image files themselves into memory
- Adding includes(:avatar_attachment) alone is enough to render variant thumbnails without extra queries
- with_all_variant_records is a model-level scope you call on Freelancer
- strict_loading: true on has_one_attached validates that an avatar is attached