Rails ActiveSorage:在所有者记录被销毁后,如何保留附件?

时间:2019-05-21 12:38:57

标签: ruby-on-rails rails-activestorage

Rails API文档针对has_many_attachedhas_one_attched方法声明了the following

  

如果未设置:dependent选项,那么只要销毁记录,所有附件都会被清除(即销毁)。

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

2 个答案:

答案 0 :(得分:2)

我假设您正在使用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

将清除photo

has_one_attached :photo, dependent: :purge_later

将导致照片被清除。

has_one_attached :photo, dependent: :detach

将导致照片分离,但活动存储区仍保持不变。

请注意,:purge_later以外的任何内容都将导致附件被分离而不是被清除。所以不正确:

has_one_attached :photo, dependent: :purge

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

该代码似乎已经在Rails 6中经过了重大的重构,因此可能已经解决了这种奇怪的情况。

答案 1 :(得分:0)

添加:nullify可能会帮助您解决问题。查看文档:{​​{3}}

相关问题