In a Rails model, what does has_one_attached :avatar set up, and which tables hold the uploaded file's data?
answer
- no column on the model's table
- polymorphic join row per attachment
- blob row: key, byte_size, checksum
- bin/rails active_storage:install
- upload runs after commit
basics
~20 shas_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 linesclass 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_sizego deeper
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.
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.
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.
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