In Active Storage, how is a named variant such as :thumb on has_one_attached generated, stored and reused?
answer
- attachable.variant inside the macro's block
- lazy: processed on first request
- variant_records keyed by variation_digest
- preprocessed: true enqueues TransformJob
- libvips via image_processing
basics
~20 sA named variant is declared in has_one_attached's block with attachable.variant. Active Storage transforms the original with image_processing on first use, stores the result as its own blob, and records it in active_storage_variant_records so later requests reuse it.
solid answer
~40 sYou declare it in the macro's block: `has_one_attached :avatar do |attachable| attachable.variant :thumb, resize_to_fill: [96, 96] end`, then call `freelancer.avatar.variant(:thumb)`. That returns an `ActiveStorage::VariantWithRecord` without doing any work; `image_tag` builds a URL to Active Storage's representation route, and the first request downloads the original, transforms it through the `image_processing` gem on libvips, uploads the result as a new blob and creates an `active_storage_variant_records` row keyed by `blob_id` and `variation_digest`. Later requests find that row and skip processing. `.processed` forces the work now; `preprocessed: true` (Rails 7.1+) enqueues `ActiveStorage::TransformJob` after the attachment commits. An unknown name raises `ArgumentError`; a non-image such as a PDF raises `ActiveStorage::InvariableError`, so use `preview` or `representation` there.
code
ruby · 12 linesclass Freelancer < ApplicationRecord
has_one_attached :avatar do |attachable|
attachable.variant :thumb, resize_to_fill: [96, 96]
attachable.variant :card, resize_to_limit: [480, 480], preprocessed: :listed?
end
end
class Contract < ApplicationRecord
has_one_attached :signed_pdf do |attachable|
attachable.variant :thumb, resize_to_limit: [200, 280]
end
endgo deeper
Recall the block syntax, attachable.variant :thumb with resize_to_limit or resize_to_fill, and that image_tag record.avatar.variant(:thumb) is how a view shows it.
Explain lazy processing, the variant record keyed by variation_digest, what processed forces, and when to reach for preprocessed: or preview instead of variant.
Discuss where the processing cost lands (first request, page render or a job), untrusted image loaders after 8.1.3.1, and never letting request parameters choose transformations.
Judge whether on-demand variants suit the product or whether a fixed set produced at upload time, with its storage cost, gives more predictable latency and capacity.
## Declaring named variants A **variant** is a transformed copy of an image attachment: resized, cropped, converted. A **named variant** gives a set of transformations a name on the attachment declaration, so views ask for `:thumb` instead of repeating sizes: ```ruby class Freelancer < ApplicationRecord has_one_attached :avatar do |attachable| attachable.variant :thumb, resize_to_fill: [96, 96] attachable.variant :card, resize_to_limit: [480, 480], preprocessed: true end end ``` The transformation keys come from the **image_processing** gem, which Active Storage drives: `resize_to_limit` (shrink to fit, never enlarge), `resize_to_fit` (fit, enlarging if needed), `resize_to_fill` (fill the box and crop the overflow), `resize_and_pad`, `crop`, `rotate`, plus `format:` and processor-specific `saver:` options. A new app's Gemfile carries `gem "image_processing", "~> 1.2"`, and the generated Dockerfile installs `libvips`. ## What happens when a view asks for one `freelancer.avatar.variant(:thumb)` looks the name up on the attachment's reflection and calls `blob.variant` with those transformations. It returns an object; it does **not** transform anything yet. 1. `image_tag freelancer.avatar.variant(:thumb)` builds a URL to Active Storage's representation route, carrying the signed blob id and an encoded variation key. 2. The browser requests that URL. Active Storage's representation controller calls `processed` on the variant. 3. `processed` checks for an existing **variant record**. If none exists, it downloads the original, runs the transformation, uploads the output under a new blob, and creates a row in `active_storage_variant_records` (`blob_id`, `variation_digest`) whose `image` attachment points at the new blob. 4. The response then serves the processed file. Every later request finds the variant record and skips step 3. In a view you can also call `freelancer.avatar.variant(:thumb).processed.url` to force processing during the current request and get a service URL directly; on a page with many images this moves the transformation cost into the page render. ## The settings that shape it | Setting | Rails 8.1 value | Effect | |---|---|---| | `config.active_storage.track_variants` | `true` (since `load_defaults 6.1`) | variants recorded in `active_storage_variant_records`; `variant` returns `VariantWithRecord` | | `config.active_storage.variant_processor` | `:vips` (since `load_defaults 7.0`) | libvips through `ruby-vips`; `:mini_magick` is the alternative | | `config.active_storage.variable_content_types` | PNG, GIF, JPEG, TIFF, BMP, PSD, ICO, WebP, AVIF, HEIC, HEIF | only these can have variants | | `config.active_storage.web_image_content_types` | PNG, JPEG, GIF, WebP (WebP since `load_defaults 7.2`) | other variable types are converted to PNG unless `format:` says otherwise | Without variant tracking, `variant` returns a plain `ActiveStorage::Variant` and existence is checked against the storage service instead of the database. ## preprocessed: and conditional preprocessing Lazy processing means the first visitor pays for the resize. **`preprocessed: true`**, added in Rails 7.1, moves that to a job: when the attachment row commits, `transform_variants_later` enqueues `ActiveStorage::TransformJob` for each preprocessed variant. The option also takes a method name (`preprocessed: :published?`) or a proc that receives the record, so only some records pay for eager processing. ## Errors and edge cases - **Unknown name.** `avatar.variant(:huge)` raises `ArgumentError` ("Cannot find variant :huge for Freelancer#avatar"). - **Not an image.** A signed contract PDF is not in `variable_content_types`, so `variant` raises `ActiveStorage::InvariableError`. Check `variable?` first, or use **`preview(:thumb)`**, which renders the first page of a PDF (Poppler or MuPDF) or a video frame (FFmpeg) and then applies the transformations, or **`representation(:thumb)`**, which picks preview or variant for you. Those system tools are not installed by Rails. - **Untrusted loaders.** Since 8.1.3.1 Active Storage calls `Vips.block_untrusted(true)` at boot and requires libvips 8.13 and ruby-vips 2.2.1 or newer; BMP, ICO and PSD variants then raise `Vips::Error` on platforms where libvips reads them through ImageMagick. - **User input.** Never build transformation hashes from request parameters; the guide warns that arbitrary processor options can open command-injection paths. ## Lifecycle of variant files With tracking on, a variant's file is an ordinary blob attached as `image` to an `ActiveStorage::VariantRecord`. When the original blob is destroyed, a `before_destroy` callback destroys its variant records, and their `image` attachments purge the variant blobs in the background; untracked variants live under a `variants/<key>/` prefix that `Blob#delete` removes. Changing a named variant's options produces a new `variation_digest`, so the next request generates a fresh file; the old variant record and its blob stay until the original is purged.
- What does representation(:thumb) do that variant(:thumb) does not?`representation` checks the blob: if a previewer accepts it (PDF, video) it returns a `preview`, if the content type is variable it returns a `variant`, and otherwise it raises `ActiveStorage::UnrepresentableError`. It lets one view line handle avatars and contract PDFs alike, where `variant` alone would raise `InvariableError` for the PDF.
- Why might a page that calls .processed.url on every thumbnail be slow on its first render?`processed` performs any missing transformation inside the current request: download the original, resize with libvips, upload the result, create the variant record. On a fresh listing that work happens once per image during the page render. Lazy URLs push it to separate image requests, and `preprocessed: true` pushes it into `TransformJob` before anyone asks.
- Where does a variant's file go when you edit the :thumb dimensions?New options give a new `variation_digest`, so the next request generates and stores a new variant blob with its own variant record. The old variant record and its blob are not removed by the edit; they stay until the original blob is destroyed, which destroys its variant records and purges their blobs.
A named variant is like a print shop's standing order: the first customer who asks for a wallet-size print waits while it is made, the shop files the print under the negative's number, and everyone after that gets the filed copy.
- Calling variant(:thumb) resizes the image immediately inside that method call
- preprocessed: true resizes the image synchronously inside the save request
- Variants overwrite the original blob so only one copy of the image is kept
- A PDF attachment can be passed to variant directly, since Active Storage converts it automatically
- A new Rails 8.1 app uses MiniMagick as its default variant processor
Assumes Rails 8.1.4 with load_defaults 8.1: track_variants true (since 6.1), :vips processor (since 7.0), preprocessed: available since 7.1, untrusted vips loaders blocked since 8.1.3.1.