Class: ActiveStorage::Attachment

Inherits:
Record show all
Defined in:
activestorage/app/models/active_storage/attachment.rb

Overview

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

Constant Summary

Constants included from ActiveModel::Translation

ActiveModel::Translation::MISSING_TRANSLATION

Constants included from ActiveRecord::Querying

ActiveRecord::Querying::QUERYING_METHODS

Constants included from ActiveRecord::ConnectionHandling

ActiveRecord::ConnectionHandling::DEFAULT_ENV, ActiveRecord::ConnectionHandling::RAILS_ENV

Constants included from ActiveRecord::SecureToken

ActiveRecord::SecureToken::MINIMUM_TOKEN_LENGTH

Constants included from ActiveRecord::Transactions

ActiveRecord::Transactions::ACTIONS

Constants included from ActiveModel::SecurePassword

ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED

Constants included from ActiveRecord::Callbacks

ActiveRecord::Callbacks::CALLBACKS

Constants included from ActiveRecord::AttributeMethods

ActiveRecord::AttributeMethods::RESTRICTED_CLASS_METHODS

Constants included from ActiveModel::AttributeMethods

ActiveModel::AttributeMethods::CALL_COMPILABLE_REGEXP, ActiveModel::AttributeMethods::FORWARD_PARAMETERS, ActiveModel::AttributeMethods::NAME_COMPILABLE_REGEXP

Instance Attribute Summary

Attributes included from ActiveRecord::ConnectionHandling

#connection_specification_name

Attributes included from ActiveRecord::Transactions

#_new_record_before_last_commit

Attributes included from ActiveRecord::Core

#strict_loading_mode

Instance Method Summary collapse

Methods included from ActiveRecord::Aggregations::ClassMethods

#composed_of

Methods included from ActiveRecord::Delegation::DelegateCache

#generate_relation_method, #inherited, #initialize_relation_delegate_cache, #relation_delegate_class

Methods included from ActiveRecord::Enum

#enum, extended, #load_schema!

Methods included from ActiveRecord::Explain

#collecting_queries_for_explain, #exec_explain

Methods included from ActiveRecord::DelegatedType

#delegated_type

Methods included from ActiveRecord::Translation

#i18n_scope, #lookup_ancestors

Methods included from ActiveModel::Translation

#human_attribute_name, #i18n_scope, #lookup_ancestors

Methods included from ActiveModel::Naming

extended, #model_name, param_key, plural, route_key, singular, singular_route_key, uncountable?

Methods included from ActiveRecord::Querying

#_load_from_sql, #_query_by_sql, #async_count_by_sql, #async_find_by_sql, #count_by_sql, #find_by_sql

Methods included from ActiveRecord::QueryCache::ClassMethods

#cache, #uncached

Methods included from ActiveRecord::ConnectionHandling

#clear_active_connections!, #clear_all_connections!, #clear_cache!, #clear_query_caches_for_current_thread, #clear_reloadable_connections!, #connected?, #connected_to, #connected_to?, #connected_to_many, #connecting_to, #connection, #connection_db_config, #connection_pool, #connects_to, #establish_connection, #flush_idle_connections!, #primary_class?, #prohibit_shard_swapping, #remove_connection, #retrieve_connection, #shard_swapping_prohibited?, #while_preventing_writes

Methods included from ActiveSupport::DescendantsTracker

clear, #descendants, descendants, disable_clear!, reject!, store_inherited, subclasses, #subclasses

Methods included from ActiveSupport::DescendantsTracker::ReloadedClassesFiltering

#descendants, #subclasses

Methods included from ActiveSupport::Benchmarkable

#benchmark

Methods included from ActiveRecord::Marshalling::Methods

#_marshal_dump_7_1, #marshal_load

Methods included from ActiveRecord::Normalization

#normalize_attribute

Methods included from ActiveSupport::Concern

#append_features, #class_methods, extended, #included, #prepend_features, #prepended

Methods included from ActiveRecord::Suppressor

registry, #save, #save!

Methods included from ActiveRecord::SignedId

#signed_id

Methods included from ActiveRecord::TokenFor

#generate_token_for

Methods included from ActiveRecord::Serialization

#serializable_hash

Methods included from ActiveModel::Serializers::JSON

#as_json, #from_json

Methods included from ActiveModel::Serialization

#serializable_hash

Methods included from ActiveRecord::Reflection

add_aggregate_reflection, add_reflection, create

Methods included from ActiveRecord::NoTouching

applied_to?, apply_to, #no_touching?, #touch, #touch_later

Methods included from ActiveRecord::TouchLater

#before_committed!, #touch, #touch_later

Methods included from ActiveRecord::Transactions

#before_committed!, #committed!, #destroy, #rolledback!, #save, #save!, #touch, #transaction, #trigger_transactional_callbacks?, #with_transaction_returning_status

Methods included from ActiveRecord::NestedAttributes

#_destroy

Methods included from ActiveRecord::AutosaveAssociation

#changed_for_autosave?, #destroyed_by_association, #destroyed_by_association=, #mark_for_destruction, #marked_for_destruction?, #reload

Methods included from ActiveRecord::Associations

#association, #association_cached?, eager_load!, #initialize_dup

Methods included from ActiveSupport::Autoload

#autoload, #autoload_at, #autoload_under, #eager_autoload, #eager_load!, extended

Methods included from ActiveRecord::Timestamp

#initialize_dup

Methods included from ActiveRecord::Callbacks

#destroy, #increment!, #touch

Methods included from ActiveRecord::AttributeMethods

#[], #[]=, #_has_attribute?, #accessed_fields, #attribute_for_inspect, #attribute_names, #attribute_present?, #attributes, dangerous_attribute_methods, #has_attribute?, #respond_to?

Methods included from ActiveModel::AttributeMethods

#attribute_missing, #method_missing, #respond_to?, #respond_to_without_attributes?

Methods included from ActiveRecord::Encryption::EncryptableRecord

#ciphertext_for, #decrypt, #encrypt, #encrypted_attribute?

Methods included from ActiveRecord::Locking::Pessimistic

#lock!, #with_lock

Methods included from ActiveRecord::Locking::Optimistic

#increment!, #initialize_dup, #locking_enabled?

Methods included from ActiveRecord::Validations

#save, #save!, #valid?

Methods included from ActiveModel::Validations

#errors, #initialize_dup, #invalid?, #valid?, #validate!, #validates_with

Methods included from ActiveRecord::Integration

#cache_key, #cache_key_with_version, #cache_version, #to_param

Methods included from ActiveModel::Conversion

#to_key, #to_model, #to_param, #to_partial_path

Methods included from ActiveModel::AttributeAssignment

#assign_attributes

Methods included from ActiveRecord::Scoping

#initialize_internals_callback, #populate_with_current_scope_attributes

Methods included from ActiveRecord::Inheritance

#initialize_dup

Methods included from ActiveRecord::ModelSchema

derive_join_table_name

Methods included from ActiveRecord::Persistence

#becomes, #becomes!, #decrement, #decrement!, #delete, #destroy, #destroy!, #destroyed?, #increment, #increment!, #new_record?, #persisted?, #previously_new_record?, #previously_persisted?, #reload, #save, #save!, #toggle, #toggle!, #touch, #update, #update!, #update_attribute, #update_attribute!, #update_column, #update_columns

Methods included from ActiveRecord::Core

#<=>, #==, #blank?, #connection_handler, #encode_with, #freeze, #frozen?, #hash, #init_with, #init_with_attributes, #initialize, #initialize_dup, #inspect, #present?, #pretty_print, #readonly!, #readonly?, #strict_loading!, #strict_loading?, #strict_loading_n_plus_one_only?

Methods included from ActiveModel::Access

#slice, #values_at

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class ActiveModel::AttributeMethods

Instance Method Details

#preview(transformations) ⇒ Object

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.



85
86
87
88
# File 'activestorage/app/models/active_storage/attachment.rb', line 85

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

#purgeObject

Synchronously deletes the attachment and purges the blob.



35
36
37
38
39
40
41
# File 'activestorage/app/models/active_storage/attachment.rb', line 35

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

#purge_laterObject

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



44
45
46
47
48
49
50
# File 'activestorage/app/models/active_storage/attachment.rb', line 44

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

#representation(transformations) ⇒ Object

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

avatar.representation(resize_to_limit: [100, 100]).processed.url

or if you are using pre-defined variants:

avatar.representation(:thumb).processed.url

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.



104
105
106
107
# File 'activestorage/app/models/active_storage/attachment.rb', line 104

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

#variant(transformations) ⇒ Object

Returns an ActiveStorage::Variant or ActiveStorage::VariantWithRecord instance for the attachment with the set of transformations provided. Example:

avatar.variant(resize_to_limit: [100, 100]).processed.url

or if you are using pre-defined variants:

avatar.variant(:thumb).processed.url

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.



66
67
68
69
# File 'activestorage/app/models/active_storage/attachment.rb', line 66

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