In Active Storage, how do purge, purge_later and detach differ, and what happens to the files when the owning record is destroyed?
answer
- detach keeps blob and file
- purge: synchronous service call
- purge_later enqueues ActiveStorage::PurgeJob
- dependent: :purge_later is the default
- has_many assignment replaces, attach appends
basics
~20 sdetach 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).
solid answer
~40 sAll three remove the `active_storage_attachments` row. `detach` stops there, leaving the blob and its file as an unattached blob. `purge` also destroys the blob row (with its variant records) and deletes the file from the service in the same call, which means a network request, so Rails advises against it inside transactions or callbacks. `purge_later` deletes the attachment now and enqueues `ActiveStorage::PurgeJob`, which calls `blob.purge` in the background. When the owner is destroyed, the attachment rows are destroyed and the macro's `dependent:` option decides the blob's fate: `:purge_later` by default, `:purge` for synchronous deletion, `false` to keep the files. Replacing or clearing an attachment (`update!(avatar: nil)`) follows the same `dependent:` rule, and in Rails 8.1 assigning to a `has_many_attached` replaces the set while `attach` appends.
code
ruby · 13 linesclass Freelancer < ApplicationRecord
has_one_attached :avatar # dependent: :purge_later
has_many_attached :portfolio_images
end
class Contract < ApplicationRecord
has_one_attached :signed_pdf, dependent: false # keep signed copies
end
freelancer.avatar.purge_later # row gone now, file removed by PurgeJob
freelancer.avatar.detach # row gone, blob and file stay (unattached)
freelancer.portfolio_images.attach(new_photo) # appends
freelancer.update!(portfolio_images: [new_photo]) # replaces the whole setgo deeper
Recall the three calls and what each leaves behind, and that destroying a record purges its files later by default.
Explain dependent: :purge_later, :purge and false, why purge makes a network call, how PurgeJob runs, and replace-versus-append on has_many_attached.
Show production judgment: never purge inline inside transactions, keep records that need retention with dependent: false, and schedule an unattached-blob sweep you can afford on a large table.
Decide a retention policy for user files across deletion, legal holds and restores, and how Active Storage's dependent options and cleanup jobs implement it.
## Three ways to remove an attachment An attachment has three layers: the **attachment row** linking a record to a blob, the **blob row** describing the file, and the **file** (plus any variant files) in the storage service. The removal methods differ in how many layers they take away and when. | Call | Attachment row | Blob row | File in service | When | |---|---|---|---|---| | `freelancer.avatar.detach` | deleted | kept | kept | now | | `freelancer.avatar.purge` | deleted | destroyed | deleted | now, inline | | `freelancer.avatar.purge_later` | deleted | destroyed | deleted | blob work in `ActiveStorage::PurgeJob` | All three are available on `has_one_attached` and `has_many_attached` proxies; on a `has_many_attached` they act on every attachment in the collection. `purge` and `purge_later` also touch the owning record so its `updated_at` changes. ## Why purge_later is the usual choice `Blob#purge` destroys the blob row, which with variant tracking on also destroys its variant records and purges their image blobs, and then calls `delete`, which asks the storage service to remove the object (and the `variants/<key>/` prefix that untracked variants use). The source comment is direct: deleting the file "will initiate an HTTP connection to the service, which may be slow or prevented, so you should not use this method inside a transaction or in callbacks". Holding row locks while waiting on an object store is how a slow bucket turns into database contention. `purge_later` deletes the attachment row immediately, so the record no longer shows the file, and enqueues **`ActiveStorage::PurgeJob`**. That job runs `blob.purge`, discards itself on `ActiveRecord::RecordNotFound` (the blob is already gone) and retries on `ActiveRecord::Deadlocked`. Its queue is `config.active_storage.queues.purge`, which `load_defaults 6.1` sets to `nil`, meaning the default queue. `detach` is for the opposite intent: you want the file to survive. The blob becomes **unattached** and can be attached elsewhere by its `signed_id`, or swept up later by a cleanup task. ## What destroying the owner does `has_one_attached` and `has_many_attached` take a **`dependent:`** option: - `:purge_later` (the default) enqueues a purge for each blob after the attachment's destroy commits; - `:purge` purges inline in that after-commit callback; - `false` destroys the attachment rows but leaves blobs and files in place, for example for signed contracts that must be retained after an account closes. The attachment association itself is always `dependent: :destroy`; the option above only governs the blob. The same callback fires when an attachment is **replaced or cleared**: 1. `freelancer.avatar.attach(new_file)` on a record that already has an avatar swaps the attachment, and the old blob is purged according to `dependent:`. 2. `freelancer.update!(avatar: nil)` or `update!(avatar: "")` removes the attachment and, with the default, enqueues a `PurgeJob` for the old blob. 3. With `dependent: false`, both of the above leave the old blob stored. ## has_many_attached: replace versus append For `has_many_attached :portfolio_images`: - `portfolio.portfolio_images.attach(file)` **appends** to the existing images. - `portfolio.update!(portfolio_images: [file])`, including a form submit, **replaces** the set; removed attachments are destroyed and their blobs purged per `dependent:`. Rails 6.0 introduced replace-on-assign behind `config.active_storage.replace_on_assign_to_many`; that switch was deprecated and then removed in Rails 7.2, so replacement is simply how assignment works now. To keep existing images through an edit form, render a hidden field per image carrying its `signed_id` alongside the file field. ## Shared blobs and leftovers - A blob attached to two records is protected by the foreign key from `active_storage_attachments.blob_id`; `Blob#purge` rescues `ActiveRecord::InvalidForeignKey`, so purging one owner's attachment leaves a still-referenced blob in place. - Detached blobs and abandoned direct uploads accumulate. `ActiveStorage::Blob.unattached` (a `where.missing(:attachments)` scope) finds them; the guide's example sweeps those older than two days with `find_each(&:purge_later)` and warns that the query can be slow on large databases. - Purging is irreversible for the file. If a record is soft-deleted or must be restorable, use `dependent: false` and purge on a retention schedule instead.
- A Contract uses has_one_attached :signed_pdf, dependent: false. What happens to the PDF when the contract row is destroyed?The `active_storage_attachments` row is destroyed, because the association is always `dependent: :destroy`, but no purge runs. The blob row and the stored PDF remain as an unattached blob, findable through `ActiveStorage::Blob.unattached`, until something purges it on purpose.
- Why can purge_later still leave a file in storage?The job may not run or may stop early: no worker is processing the queue, the blob row was already deleted without its file, or the blob is still attached to another record so the foreign key blocks its deletion and `purge` rescues `InvalidForeignKey`. Monitoring the purge queue and running an unattached-blob sweep covers these gaps.
- detach deletes the stored file but keeps the attachment row for history
- purge only removes the attachment row and leaves the blob row in place
- Destroying the owning record leaves its files in storage unless you add a callback
- In Rails 8.1 assigning a has_many_attached appends unless replace_on_assign_to_many is set
- purge is the safe choice inside an after_destroy callback because it runs in the transaction
Assumes Rails 8.1; has_many_attached assignment always replaces because config.active_storage.replace_on_assign_to_many was removed in Rails 7.2.