如何从回形针文件中动态设置preserve_files选项



在我的项目中,我将回形针与偏执狂 gem 一起使用(以便软删除某些模型)。在此模型中,我同时使用这两个宝石:

class Material < ActiveRecord::Base
    has_attached_file :material, preserve_files: true
    acts_as_paranoid
    validates_attachment :material, presence: true
end

偏执狂 gem 提供了一种硬删除对象的方法:really_destroy! 方法。但是,当我调用此方法时,对象被删除,但文件保留。我是什么删除文件太。例:

@material_a.destroy # soft-delete the object and preserve the file
@material_b.really_destroy! # hard-delete the object and delete the file

有没有办法动态设置回形针preserve_files选项?

似乎您无法动态设置 :p reserve_files 选项,但还有另一种方法可以执行您想要的操作。

回形针通过首先设置要删除的路径队列,然后在保存对象时删除附件来删除附件。如果同一对象有多种样式(例如,图像文件的大小不同),则对象可以有多个要删除的路径。如果你调用 #destroy 或 #clear(不带参数),它将调用#queue_all_for_delete,检查是否设置了:p reserve_files。但是,如果您调用带有要删除的样式列表的 #clear,它将调用 #queue_some_for_delete,它不会检查 :p reserve_files。

因此,我们只需要为 #clear 提供所有样式的列表:

all_styles = @material_b.attachment.styles.keys.map { |key|
    @material_b.attachment.styles[key].name
} << :original
@material_b.attachment.clear(*all_styles)
@material_b.save
@material_b.really_destroy!

这就是答案

has_attached_file :image, :styles => { :medium => "300x300#", :thumb => "100x100#", :small => "100x100#", :large => "500x500>"}, :convert_options => { :medium => "-quality 80 -interlace Plane", :thumb => "-quality 80 -interlace Plane" }, :default_url => "./public/images/avatar.png", :preserve_files => true, :processors => [:cropper]

您只需要添加而无需任何额外的宝石

:preserve_files => true

最新更新