Another way to do so is to override has_many
of attachments:
class Employee < ApplicationRecord
acts_as_paranoid
# Override the `has_many` association for Active Storage attachments
has_many_attached :files do
has_many :files_attachments,
-> { where(name: name) },
as: :record,
class_name: "ActiveStorage::Attachment",
inverse_of: :record,
dependent: nil, # Disable default deletion behavior (defined by `has_many_attached` method)
strict_loading: false
has_many :files_blobs,
through: :files_attachments,
class_name: "ActiveStorage::Blob",
source: :blob,
strict_loading: false
end
# Ensure attachments are purged after permanent deletion (not soft-deletion)
after_real_destroy :purge_attachments
private
def purge_attachments
files_attachments.each(&:purge_later)
end
end
Similarly, for has_one_attached
, override the has_one
method
See https://github.com/rails/rails/blob/main/activestorage/lib/active_storage/attached/model.rb