Preventing Paperclip from deleting/overwriting attachments on update

后端 未结 4 924
灰色年华
灰色年华 2020-12-30 01:39

I\'m having a hard time figuring out how to prevent Paperclip from deleting the old version of an attachment (image).

I have a model, Site, which has an attachment,

4条回答
  •  孤城傲影
    2020-12-30 02:40

    Because attachments are defined at the class level, Paperclip interpolates the symbols in your strings using it's own interpolation library. You can create your own interpolations using this library.

    I would add a field to the model called attachment_version or something similar, and then increment this version number each time the file is changed. Then, create an interpolation for it in an initializer file:

    Paperclip.interpolates :version do |attachment, style|
      attachment.instance.attachment_version
    end
    

    Now you can use :version in your strings:

    class Model < ActiveRecord::Base
      has_attached_file :something, :path => " :rails_root/public/somethings/etc/:version.:extension"
    end
    

    See the wiki documentation for more information.

    [Update]

    After some digging around (see the comments to this answer), I've come to the conclusion that Paperclip will still delete the old attachment due to code that's called in Paperclip::Atachment#attach. Probably the best way to deal with this is to create a new storage engine based on Paperclip::Storage::Filesystem and overwrite #flush_deletes. Note that there is no way in that method to tell if a file is being queued for deletion because of the model it belongs to being deleted or a new file is being uploaded in its place.

提交回复
热议问题