Mar 19, 2013

Purge ActiveStorage Attachment by Attribute

I love ActiveModel::Attributes.

Recently, I had a model with many attachments.

has_one_attached :design
has_one_attached :colormap
has_one_attached :bmp_1
has_one_attached :bmp_2

And I wanted a user to be able to delete an attachment from the form. I had a few options:

  1. Do something with a new routing endpoint
  2. Use ActiveModel::Attributes

I obviously chose the latter.

From this:

[:design, :colormap, :bmp_1, :bmp_2].each do |type|
  attribute "purge_#{type}", :boolean, default: false
  after_commit if: :"purge_#{type}?" do
    self.send("purge_#{type}=", false)
    send(type).purge_later
  end
end

To:

purgeable_attachments :design