Rails 4: Validate that an image to upload is unique
If you want to verify you already uploaded the same image before, this is an easy way to do it:
- Create a migration to store the SHA-1 of the image:
rails g migration add_image_sha1_to_my_model image_sha1:string
- Calculate SHA-1 on the model:
before_validation(on: :create) do
self.sha1 = Digest::SHA1.file(image.path).hexdigest
end
- Create an custom validator for the image (it can be used for other images):
class ImageValidator < ActiveModel::Validator
def validate(image)
image.errors.add(:image, 'already exists') if image.class.exists?(sha1: image.sha1)
end
end
- Add the validation to the model:
class MyModel < ActiveRecord::Base
validates_with ImageValidator
end
Written by Lucia Escanellas
Related protips
2 Responses

Very useful snippet, thanks!
over 1 year ago
·

It would be nice also to compare some meta information of the image so it doesn't matter if you changed the path of the image
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Rails
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#