skip to content

Attachments & Variants

has_one_attached and has_many_attached link records to blobs through join tables, and variants resize images on demand with libvips. Interviewers ask about direct uploads, purging and attachment N+1.

part ofRuby on Railsread it →
on this pageshow

explore

questions

6

In a Rails model, what does has_one_attached :avatar set up, and which tables hold the uploaded file's data?

level: juniorimportance: must knowfreq 72%

answer

  1. no column on the model's table
  2. polymorphic join row per attachment
  3. blob row: key, byte_size, checksum
  4. bin/rails active_storage:install
  5. upload runs after commit

basics

~20 s

has_one_attached :avatar adds no column; it defines an avatar_attachment association to a polymorphic row in active_storage_attachments, which points at a row in active_storage_blobs describing the file. The bytes themselves live in the configured storage service.

solid answer

~30 s

`has_one_attached :avatar` adds no column to the model's table. It defines a `has_one :avatar_attachment` (an `ActiveStorage::Attachment` row whose polymorphic `record_type`/`record_id` point back at the model and whose `name` is `"avatar"`) and a `has_one :avatar_blob, through:` that reaches the `ActiveStorage::Blob`. The blob row stores the file's `key`, `filename`, `content_type`, `byte_size`, `checksum`, `metadata` and `service_name`; the bytes go to the storage service. `freelancer.avatar` returns an `ActiveStorage::Attached::One` proxy with `attach`, `attached?`, `purge` and `variant`. The tables come from `bin/rails active_storage:install` plus `bin/rails db:migrate`, which also adds `active_storage_variant_records`. A file assigned to an unsaved record is uploaded only after the record's save commits.

code

ruby · 14 lines
ruby
class Freelancer < ApplicationRecord
  has_one_attached :avatar
  has_many_attached :portfolio_images
end

freelancer = Freelancer.create!(name: "Ana")
freelancer.avatar.attach(
  io: File.open(Rails.root.join("db/seeds/ana.jpg")),
  filename: "ana.jpg",
  content_type: "image/jpeg"
)
freelancer.avatar.attached?    # => true
freelancer.avatar_attachment   # => #<ActiveStorage::Attachment name: "avatar", record_type: "Freelancer", ...>
freelancer.avatar_blob.byte_size

go deeper

for a junior

Recall the three table names, that the model gets no column, and the attach and attached? calls, including attach with io: and filename: for files that never came from a form.

for a middle

Explain the generated associations (avatar_attachment, avatar_blob), the polymorphic record_type, and that uploads happen after commit so a failed save stores nothing for a request upload.

for a senior

Show you know the consequences in production: class renames need a record_type data migration, shared blobs are protected by the foreign key, and listing pages need preloading.

for a principal

Weigh Active Storage's generic join-table design against a dedicated column or table per file type, considering query cost, reporting and moving storage backends later.

## What the macro declares In a freelancer marketplace, a profile photo is declared like this: ```ruby class Freelancer < ApplicationRecord has_one_attached :avatar end ``` **`has_one_attached`** does not touch the `freelancers` table at all: there is no `avatar` column, no file path and no foreign key on the model's side. Instead the macro generates, inside the model: - `has_one :avatar_attachment`, an `ActiveStorage::Attachment` scoped to `name: "avatar"`, with `dependent: :destroy`; - `has_one :avatar_blob, through: :avatar_attachment`, the `ActiveStorage::Blob` behind it; - a reader `avatar` that returns an **`ActiveStorage::Attached::One`** proxy, and a writer `avatar=` that records a pending change; - a scope `with_attached_avatar` for preloading; - an `after_save` that writes the attachment rows and an `after_commit` that uploads any pending file. `has_many_attached :portfolio_images` does the same with plural names (`portfolio_images_attachments`, `portfolio_images_blobs`) and an `ActiveStorage::Attached::Many` proxy. The model generator understands the type too: `bin/rails generate model Freelancer name:string avatar:attachment` writes the `has_one_attached` line and creates no column for it. ## The three tables A new app does not create them; you run `bin/rails active_storage:install` and then `bin/rails db:migrate`. | Table | One row per | Key columns | |---|---|---| | `active_storage_blobs` | stored file | `key` (unique), `filename`, `content_type`, `metadata`, `service_name`, `byte_size`, `checksum` | | `active_storage_attachments` | link between a record and a blob | `name`, `record_type`, `record_id`, `blob_id` | | `active_storage_variant_records` | generated variant of a blob | `blob_id`, `variation_digest` | The attachments table is a **polymorphic join table**: `record_type` stores the owning class name (`"Freelancer"`), so renaming the class means updating those rows too. A unique index on `record_type, record_id, name, blob_id` and a foreign key from `blob_id` to the blobs table keep the links consistent. The **blob** is only metadata: `key` names the object in the storage service, `checksum` is a Base64 MD5 of the content, and `service_name` records which service in `config/storage.yml` holds it. ## Attaching a file `attach` accepts several kinds of input: ```ruby freelancer.avatar.attach(params[:freelancer][:avatar]) # an uploaded file freelancer.avatar.attach(params[:signed_blob_id]) # a direct upload's signed id freelancer.avatar.attach( io: File.open(Rails.root.join("tmp/headshot.jpg")), filename: "headshot.jpg", content_type: "image/jpeg" ) # any IO freelancer.avatar.attached? # => true ``` The `io:` hash form is how files that never came through a form get attached: a PDF the app generated, a file downloaded in a job, a seed image. Active Storage computes the checksum and size from the IO and identifies the content type from the bytes, using the declared `content_type` as a hint; `identify: false` skips that sniffing. When and how the save happens: 1. If the record is **persisted and has no other unsaved changes**, `attach` saves it immediately and returns the proxy, or `nil` if the save fails. 2. Otherwise the attachment is held as a pending change and written on the record's next `save`. 3. The bytes are sent to the service in an **`after_commit`** callback, so a failed validation or a rolled-back transaction uploads nothing for a file that arrived with the request. 4. After the attachment row commits, Active Storage enqueues analysis (`analyze_later`, which fills `metadata` with width and height for images) and any preprocessed variants. ## Reading it back - `freelancer.avatar.attached?` is the presence check; `freelancer.avatar.blank?` is its inverse. - `freelancer.avatar.filename`, `.content_type` and `.byte_size` are delegated through the attachment to the blob. - In a view, `image_tag freelancer.avatar` or `url_for(freelancer.avatar)` builds an Active Storage URL; how that URL is served belongs to the storage service configuration. - `Freelancer.joins(:avatar_blob).where(active_storage_blobs: { content_type: "image/png" })` filters on blob columns, because these are ordinary associations. ## Why the indirection Keeping files out of the model's table lets any model gain attachments without a migration of its own, lets one blob be attached to more than one record, and keeps the storage backend swappable: the same rows work whether `config.active_storage.service` points at disk or an object store. The cost is that each attachment is two extra rows to load, which is why listing pages need `with_attached_avatar`.

  • Why does renaming the Freelancer class break its existing avatars?
    `active_storage_attachments.record_type` stores the owning class name as a string, because the link is a polymorphic association. After a rename, rows still say `"Freelancer"`, so `Profile#avatar_attachment` finds nothing. A data migration has to update `record_type` on the matching rows in the same release as the rename.
  • What does attach return when it saves a persisted record and a validation fails?
    It returns `nil`. `Attached::One#attach` calls `record.save` when the record is persisted and otherwise unchanged, and returns early if that save is false; on success it returns the attachment proxy. Because the upload runs in `after_commit`, a file that arrived with the request is not sent to the service when the save fails.
  • Can two records point at the same blob?
    Yes. Attaching an existing `ActiveStorage::Blob` (or its signed id) to a second record creates a second attachment row with the same `blob_id`. The foreign key from attachments to blobs then stops the blob row from being deleted while either attachment exists, and `Blob#purge` rescues the resulting `ActiveRecord::InvalidForeignKey`.

  • has_one_attached needs an avatar string column migrated onto the model's table
  • The file's bytes are stored in active_storage_blobs as a binary column
  • attach uploads the file to the service before the record's validations run
  • active_storage_variant_records links a model row to its original upload
  • A new Rails app creates the Active Storage tables without any install step
open as a page

In Active Storage, how is a named variant such as :thumb on has_one_attached generated, stored and reused?

level: middleimportance: must knowfreq 56%

basics

~20 s

A 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.

open as a page

With Active Storage's direct_upload: true file field, how does the file reach the storage service, and what does the form submit to Rails?

level: middleimportance: should knowfreq 44%

basics

~20 s

Active Storage's JavaScript intercepts the submit, asks Rails to create a blob record, uploads the bytes straight to the storage service with the returned URL and headers, then submits the form with the blob's signed_id instead of the file.

open as a page

In Active Storage, how do purge, purge_later and detach differ, and what happens to the files when the owning record is destroyed?

level: middleimportance: should knowfreq 48%

basics

~20 s

detach deletes only the attachment row; purge deletes the attachment, the blob row and the stored file right away; purge_later deletes the attachment and enqueues ActiveStorage::PurgeJob for the rest. Destroying the owner purges later by default (dependent: :purge_later).

open as a page

Active Storage in Rails 8.1 has no attachment validators; how would you reject an avatar over 5 MB or a non-PDF contract?

level: middleimportance: should knowfreq 50%

basics

~20 s

Write a custom validate method that checks attachment.attached?, blob.byte_size and content_type and adds errors. The content type is sniffed from the bytes when the file is attached, and direct-uploaded files are already stored, so rejected ones need cleanup.

open as a page

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?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Each 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.

open as a page