Preventing Paperclip from deleting/overwriting attachments on update

喜夏-厌秋 提交于 2019-11-30 06:22:56

There's a new option that tells paperclip to preserve old attachments:

https://github.com/thoughtbot/paperclip/commit/65e8d4f6de50732d8e1b https://github.com/thoughtbot/paperclip/issues/60

Simple to use:

has_attached_file => :attachment,
                     :styles => { :thumb => 100x100! },
                     :preserve_files => true

It's not documented yet and took some digging to find so I wanted to share it here.

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.

I had a similar issue with Paperclip attachments at when working on a Rails blog last summer.

There is a patch that addresses this. I wasn't able to get it working for myself, but it's worth a shot!

http://github.com/alainravet/paperclip/tree/keep_old_files

lib/paperclip_monkey_patch.rb:

module Paperclip
  class Attachment
   def clear
    # nop
    #raise "hell"
    # op
    instance_write(:file_name, nil)
    instance_write(:content_type, nil)
    instance_write(:file_size, nil)
    instance_write(:updated_at, nil)
  end
 end
end

Then add this line at the top of any file that deleted attachments:

require 'paperclip_monkey_patch'

Thanks to Ruby Forum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!