Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing Paperclip from deleting/overwriting attachments on update

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, logo. I would like to keep the old logos around since I will be keeping track of changes to the model and would like to view the history of logos.

I'm keeping track of the changes in another model, which has a reference to file paths. My problem is that when updating a site with a new logo, Paperclip will flush the old logo first.

It surprises me that there's not an option you can switch to prevent Paperclip from flushing the old attachment before creating the new one.

Any ideas?

like image 330
simonwh Avatar asked Feb 06 '11 02:02

simonwh


2 Answers

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.

like image 115
Will Koehler Avatar answered Nov 07 '22 10:11

Will Koehler


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.

like image 28
Michelle Tilley Avatar answered Nov 07 '22 10:11

Michelle Tilley