简体   繁体   English

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

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

I'm using ActiveStorage to handle attachments in my rails app.我正在使用ActiveStorage处理我的 Rails 应用程序中的附件。 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).更新 model 的附件时,它似乎将清除作业排入队列,并删除远程存储服务(此处为S3 )上的先前附件。

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?我不想系统地删除我的S3存储桶中的文件(即使我的数据库中没有记录附加到它),是否可以防止这些清除作业排队?

After reading again the documentation:再次阅读文档后:

If the :dependent option isn't set, the attachment will be purged (ie destroyed) whenever the record is destroyed.如果没有设置:dependent选项,那么只要记录被销毁,附件就会被清除(即销毁)。

As stated by @yoLotus正如@yoLotus所说

If :dependent option is not set for attachement it default to :purge which cause it to delete attachment whenever related record is delete.如果没有为附件设置:dependent选项,它默认为:purge ,这会导致它在相关记录被删除时删除附件。

To overwrite this behaviour you have to set the :dependent option to :purge_later .要覆盖此行为,您必须将:dependent选项设置为: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:编写自定义 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM