Last Updated: January 28, 2019
·
1.753K
· raviolicode

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:

  1. Create a migration to store the SHA-1 of the image:

rails g migration add_image_sha1_to_my_model image_sha1:string

  1. Calculate SHA-1 on the model:
before_validation(on: :create) do
  self.sha1 = Digest::SHA1.file(image.path).hexdigest
end
  1. 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
  1. Add the validation to the model:
class MyModel < ActiveRecord::Base
  validates_with ImageValidator
end

2 Responses
Add your response

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 ·