是否可以防止 ActiveStorage 删除服务存储上的文件?

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

我正在使用 ActiveStorage 来处理我的 rails 应用程序中的附件。 更新模型的附件时,它似乎将清除作业排入队列并删除远程存储服务上以前的附件(S3 此处)。

我不希望我的 S3 存储桶中的文件被系统删除(即使我的数据库中没有记录附加到它),是否可以防止这些清除作业被排队?

再次阅读文档后:

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

如@yoLotus所述

如果没有为附件设置 :dependent 选项,它默认为 :purge,这会导致它在删除相关记录时删除附件。

要覆盖此行为,您必须将 :dependent 选项设置为 :purge_later

假设您有一个 post 附加了图像,并且您不想在 post 被删除时删除附加到 post 的图像。

这里你会怎么做:

has_one_attached :image, dependent: :purge_later

可以通过以下方式完成:

has_one_attached :photo, dependent: :detach

也可以编写自定义 S3 服务来解决问题:

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