Skip to Content Skip to Search

Attachments associate records with blobs. Usually that's a one record-many blobs relationship, but it is possible to associate many different records with the same blob. A foreign-key constraint on the attachments table prevents blobs from being purged if they’re still attached to any records.

Attachments also have access to all methods from ActiveStorage::Blob.

If you wish to preload attachments or blobs, you can use these scopes:

# preloads attachments, their corresponding blobs, and variant records (if using `ActiveStorage.track_variants`)
User.all.with_attached_avatars

# preloads blobs and variant records (if using `ActiveStorage.track_variants`)
User.first.avatars.with_all_variant_records
Methods
P
R
V

Instance Public methods

preview(transformations)

Returns an ActiveStorage::Preview instance for the attachment with the set of transformations provided. See ActiveStorage::Blob::Representable#preview for more information.

Raises an ArgumentError if transformations is a Symbol which is an unknown pre-defined variant of the attachment.

# File activestorage/app/models/active_storage/attachment.rb, line 67
def preview(transformations)
  transformations = transformations_by_name(transformations)
  blob.preview(transformations)
end

purge()

Synchronously deletes the attachment and purges the blob.

# File activestorage/app/models/active_storage/attachment.rb, line 33
def purge
  transaction do
    delete
    record.touch if record&.persisted?
  end
  blob&.purge
end

purge_later()

Deletes the attachment and enqueues a background job to purge the blob.

# File activestorage/app/models/active_storage/attachment.rb, line 42
def purge_later
  transaction do
    delete
    record.touch if record&.persisted?
  end
  blob&.purge_later
end

representation(transformations)

Returns an ActiveStorage::Preview or an ActiveStorage::Variant for the attachment with set of transformations provided. See ActiveStorage::Blob::Representable#representation for more information.

Raises an ArgumentError if transformations is a Symbol which is an unknown pre-defined variant of the attachment.

# File activestorage/app/models/active_storage/attachment.rb, line 78
def representation(transformations)
  transformations = transformations_by_name(transformations)
  blob.representation(transformations)
end

variant(transformations)

Returns an ActiveStorage::Variant or ActiveStorage::VariantWithRecord instance for the attachment with the set of transformations provided. See ActiveStorage::Blob::Representable#variant for more information.

Raises an ArgumentError if transformations is a Symbol which is an unknown pre-defined variant of the attachment.

# File activestorage/app/models/active_storage/attachment.rb, line 56
def variant(transformations)
  transformations = transformations_by_name(transformations)
  blob.variant(transformations)
end