Rails: Preventing Duplicate Photo Uploads with Paperclip?
paperclip, ruby-on-rails
Solution
What about doing an MD5 on the image file? If it is the exact same file, the MD5 hash will be the same for both images.
Problem
Is there anyway to throw a validation error if a user tries to upload the same photo twice to a Rails app using Paperclip? Paperclip doesn't seem to offer this functionality... I'm using Rails 2.3.5 and Paperclip (obviously). SOLUTION: (or one of them, at least) Using Beerlington's suggestion, I decided to go with an MD5 Checksum comparison: ``` class Photo < ActiveRecord::Base #... has_attached_file :image #, ... before_validation_on_create :generate_md5_checksum validate :unique_photo #... def generate_md5_checksum self.md5_checksum = Digest::MD5.hexdigest(image.to_file.read) end def unique_photo photo_digest = self.md5_checksum errors.add_to_base "You have already uploaded that file!" unless User.find(self.user_id).photos.find_by_md5_checksum(photo_digest).nil? end # ... end ``` Then I just added a column to my `photos` table called `md5_checksum`, and voila! Now my app throws a validation error if you try to upload the same photo! No idea how efficient/inefficient this is, so refactoring's welcome! Thanks!