ActiveStorage:所有者记录被销毁后分离(而不是清除)附件?

ActiveStorage: Detach (instead of purge) attachment after owner record is destroyed?

Rails API 文档说明 the following 关于 has_many_attachedhas_one_attched 方法:

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

具体来说,我应该为此选项指定什么值?

添加 :nullify 可能对您有用。请参阅文档:https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many-label-Options

我假设您使用的是 Rails 5.2。文档不是很好,但源代码有助于填补空白。以下是相关文件中的几行(has_one_attachedhas_many_attached 的代码相同):

# /active_storage/attached/macros.rb

def has_one_attached(name, dependent: :purge_later)

  ...

  if dependent == :purge_later
    after_destroy_commit { public_send(name).purge_later }
  else
    before_destroy { public_send(name).detach }
  end
end

根据方法定义(同样,has_one_attachedhas_many_attached 是相同的),如果没有另外指定,:dependent 将设置为 :purge_later .所以当底层记录被删除时你会得到如下结果:

has_one_attached :photo

将导致照片被清除。

has_one_attached :photo, dependent: :purge_later

将导致照片被清除。

has_one_attached :photo, dependent: :detach

将导致照片分离,但活动存储 blob 完好无损。

请注意,除 :purge_later 之外的任何内容都会导致附件被分离而不是被清除。 如此反常:

has_one_attached :photo, dependent: :purge

将导致照片分离,而不是清除

代码似乎在 Rails 6 中进行了重大重构,因此这个问题可能已得到解决。

更新:这个问题 has been submitted in Rails 5.2 and there is a pending PR