Keeping Originals after a Delete in Paperclip

This is almost certainly not of interest to the non-technical regulars here, but I’m hoping it’ll save someone down the road some time.

At work I was having a hard time with what should have been a simple problem: we use paperclip for image uploads, and create a corresponding Photo object in the database. It is not necessary to have a database backing paperclip uploads in general, but in our case, it was. (In fact, with some polymorphism, too. Many things have Photos.)

The problem is that paperclip has a feature that’s useful in 99% of cases: if you delete a Photo record (or whatever object has_attached_file), it will delete the object off of disk. This makes a lot of sense: if you tell the database to delete the reference to a photo, you probably want to get rid of the disk. The problem is that I did not. We wanted to preserve (“orphan,” a purist might argue) the image / “attached” file on disk even when you called Object.destroy.

After a while of trying to figure out how to do this in paperclip, I finally found this discussion. The answer, it turns out, is that you hack in. In the object that has the attachment (Photo for me), you override paperclip’s destroy_attached_files and just have it return true. Your neutered version takes precedence of paperclip’s, and the photos sit on disk with no reference in the database.

Incidentally, I’ve found that I’m a grumpy curmudgeon who hates tools that “just work,” largely because when they don’t “just work” in some obscure situation, it’s a real pain to try to figure out why. People always say not to fight Rails. The thing I didn’t realize is that they don’t mean, “It will create a little extra work for you.” They mean, “You will want to change careers.”

3 thoughts on “Keeping Originals after a Delete in Paperclip

  1. Does this hack actually work for you? I am trying it in my app (rails 2.3.4, paperclip latest) and paperclip still deletes the images from s3. I tried overriding both #delete_attached_files and #destroy_attached_files, with no luck either way.

  2. Yes, this works for me, and I’m running 2.3.4 too. Did you have any luck? I’ve got paperclip-2.3.1, though I’m not sure if that’s that latest.

    Does your method ever get run? (If you put a debug line or just raise an “I’m here” exception?) I don’t follow paperclip development closely enough to have any idea this functionality has been changed, but my guess is that it’s never being called for some reason.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.