ActiveStorage::Attachment (original) (raw)

Active Storage Attachment

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

B

P

R

V

W

Class Public methods

Eager load all variant records on an attachment at once.

User.first.avatars.with_all_variant_records

Source: show | on GitHub

scope :with_all_variant_records, -> { includes(blob: { variant_records: { image_attachment: :blob }, preview_image_attachment: { blob: { variant_records: { image_attachment: :blob } } }

Instance Public methods

Source: show | on GitHub

belongs_to :blob, class_name: "ActiveStorage::Blob", autosave: true, inverse_of: :attachments

Returns an ActiveStorage::Preview instance for the attachment with the set of transformations provided. Example:

video.preview(resize_to_limit: [100, 100]).processed.url

or if you are using pre-defined variants:

video.preview(:thumb).processed.url

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.

Source: show | on GitHub

def preview(transformations) transformations = transformations_by_name(transformations) blob.preview(transformations) end

Source: show | on GitHub

def purge transaction do delete record.touch if record&.persisted? end blob&.purge end

Source: show | on GitHub

def purge_later transaction do delete record.touch if record&.persisted? end blob&.purge_later end

Returns the associated record.

Source: show | on GitHub

belongs_to :record, polymorphic: true, touch: ActiveStorage.touch_attachment_records

Source: show | on GitHub

def representation(transformations) transformations = transformations_by_name(transformations) blob.representation(transformations) end

Source: show | on GitHub

def variant(transformations) transformations = transformations_by_name(transformations) blob.variant(transformations) end