2014-11-21 25 views
2

在我的項目中,我使用Paperclip和Paranoia寶石(爲了軟刪除某些模型)。在這個模型中,我使用這兩種寶石在一起:如何從Paperclip文件動態設置preserve_files選項?

class Material < ActiveRecord::Base 
    has_attached_file :material, preserve_files: true 

    acts_as_paranoid 

    validates_attachment :material, presence: true 
end 

偏執寶石提供了一種方法,硬刪除的對象: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 

有什麼辦法可以動態設置Paperclip preserve_files選項嗎?

回答

2

看來你不能動態設置:preserve_files選項,但有另一種方法可以做你想做的事。

Paperclip通過首先設置要刪除的路徑隊列,然後在保存對象時刪除它們來刪除附件。如果同一對象有多個樣式(例如不同大小的圖像文件),則對象可以有多個要刪除的路徑。如果您調用#destroy或#clear(不帶參數),它將調用#queue_all_for_delete,它檢查是否設置了preserve_files。但是,如果您將#clear與要刪除的樣式列表一起調用,它會調用#queue_some_for_delete,它不檢查:preserve_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! 
+0

絕妙的回答! – 2016-07-08 16:25:30

0

只是刪除,:preserve_files =>從您的代碼真正的,它會刪除附件,當你刪除模型反對

0

這就是答案

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 
相關問題