module JSONAPI::Relationships::ActiveStorageRemoval
def extract_blob_id_from_identifier(identifier)
def extract_blob_id_from_identifier(identifier) type = RelationshipHelpers.extract_type_from_identifier(identifier) id = RelationshipHelpers.extract_id_from_identifier(identifier) validate_blob_type!(type) id.to_i end
def extract_blob_ids(relationship_data)
def extract_blob_ids(relationship_data) relationship_data.map { |identifier| extract_blob_id_from_identifier(identifier) } end
def extract_single_blob_id(relationship_data)
def extract_single_blob_id(relationship_data) extract_blob_id_from_identifier(relationship_data) end
def remove_active_storage_relationship(relationship_data)
def remove_active_storage_relationship(relationship_data) reflection = @resource.class.reflect_on_attachment(@relationship_name) if reflection&.macro == :has_many_attached remove_many_active_storage_attachments(relationship_data) else remove_one_active_storage_attachment(relationship_data) end end
def remove_many_active_storage_attachments(relationship_data)
def remove_many_active_storage_attachments(relationship_data) raise ArgumentError, "Expected array for to-many relationship removal" unless relationship_data.is_a?(Array) return if relationship_data.empty? attachment_proxy = @resource.public_send(@relationship_name) return unless attachment_proxy.attached? blob_ids = extract_blob_ids(relationship_data) attachments = attachment_proxy.attachments.where(blob_id: blob_ids) attachments.each(&:purge) end
def remove_one_active_storage_attachment(relationship_data)
def remove_one_active_storage_attachment(relationship_data) validate_single_removal_identifier!(relationship_data) return if relationship_data.nil? attachment_proxy = @resource.public_send(@relationship_name) return unless attachment_proxy.attached? blob_id = extract_single_blob_id(relationship_data) attachment = attachment_proxy.attachments.find_by(blob_id:) attachment&.purge end
def validate_blob_type!(type)
def validate_blob_type!(type) return if self.class.active_storage_blob_type?(type) raise ArgumentError, "Expected active_storage_blobs type, got #{type}" end