Module: ActiveStorage::AwsRecord::Attachable

Extended by:
ActiveSupport::Concern
Defined in:
lib/active_storage/aws_record/attachable.rb

Overview

Mix into an aws-record model that **already manages its own persistence** (its own save/destroy — versioning, events, search) to make it an Active Storage attachment owner without the gem taking over persistence. It contributes only the owner-contract glue Active Storage’s generic builder needs: the callback chains it hooks, a changed? bridge, owner resolution, and the has_one_attached/has_many_attached macros.

class Document < BaseModel        # BaseModel already defines save/destroy
  include ActiveStorage::AwsRecord::Attachable
  has_many_attached :files

  def save(*)    = run_attachment_save    { super }
  def destroy(*) = run_attachment_destroy { delete! if persisted? }
end

The host keeps its own save/destroy, but those **must run** Active Storage’s :save (and, if defined, :commit) and :destroy callback chains — that is how attachments flush/upload and are cleaned up. If the host already runs ActiveModel :save/:destroy callbacks it works as-is; otherwise wrap raw persistence with #run_attachment_save / #run_attachment_destroy.

For a greenfield model with no persistence of its own, use Owner, which is Attachable plus an aws-record save/destroy implementation.

Assumes the host already include Aws::Record (for find_with_opts/dirty?/ hash_key). Owners must be single-hash-key (the contract stores one id).

Instance Method Summary collapse

Instance Method Details

#run_attachment_destroy(&block) ⇒ Object

Run your model’s real deletion inside the :destroy chain so attachments are cleaned up. The block must make the owner non-persisted (e.g. delete!) or Active Storage’s after_destroy cleanup is skipped (it only runs for an owner that was persisted and no longer is).



99
100
101
# File 'lib/active_storage/aws_record/attachable.rb', line 99

def run_attachment_destroy(&block)
  run_callbacks(:destroy, &block)
end

#run_attachment_saveObject

Run your model’s real save inside Active Storage’s :save chain so its attachments flush and upload (with no :commit chain the upload happens in after_save). Aborts the chain — so nothing flushes — if the save returns falsy. Returns the save result.



85
86
87
88
89
90
91
92
93
# File 'lib/active_storage/aws_record/attachable.rb', line 85

def run_attachment_save
  result = nil
  run_callbacks(:save) do
    result = yield
    throw :abort unless result
    result
  end
  result
end