Is it possible to prevent ActiveStorage from deleting file on service storage?

Viewed 911

I'm using ActiveStorage to handle attachments in my rails app. When updating the attachment of a model, it seems to enqueue a purge job and it deletes the previous attached file on the remote storage service (S3 here).

I don't want the files in my S3 bucket to be systematically deleted (even if no record is attached to it in my database), is it possible to prevent these purge job to be enqueued?

3 Answers

After reading again the documentation:

If the :dependent option isn't set, the attachment will be purged (i.e. destroyed) whenever the record is destroyed.

As stated by @yoLotus

If :dependent option is not set for attachement it default to :purge which cause it to delete attachment whenever related record is delete.

To overwrite this behaviour you have to set the :dependent option to :purge_later.

Suppose you have a post which has image attached to it and you don't want to delete attached image to post when post gets deleted.

Here how you would do it:

has_one_attached :image, dependent: :purge_later

It can be done with:

has_one_attached :photo, dependent: :detach

Reference

Also writing custom S3 service could do the trick:

require "active_storage/service/s3_service"

class ActiveStorage::Service::CustomS3Service < ActiveStorage::Service::S3Service
  attr_reader :detach
  def initialize(bucket:, upload: {}, **options)
    @detach = options[]
  end

  def delete(key)
   instrument :delete, key: key do
     detach ? object_for(key).detach : object_for(key).delete
   end
  end
end
Related