I have a User model that needs to validate the uniqueness of a field before it is saved, this field however, is changed before it is saved (it is hashed). How can I do this? I tried the following: Adding a validate digest at the end of the before save call, but that doesn’t work.
class User < ApplicationRecord
has_secure_password
before_save :downcase_email, :downcase_name, :digest_email, :validate_email_digest
validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }, presence: true
validates :name, length: { within: 2..40 }, presence: true, uniqueness: true
validates :password_digest, presence: true
self.implicit_order_column = 'created_at'
private
def validate_email_digest
# This throws an exception
validates_uniqueness_of :email, message: 'That email is already in use.'
end
def downcase_email
self.email = email.downcase
end
def downcase_name
self.name = name.downcase
end
def digest_email
self.email = Digest::SHA2.hexdigest(email).to_s
end
end
How can I validate the result of the model before_save before they are saved to the database? In this case how can I validate that the digested email is unique after it’s been digested by before_save :digest_email?
>Solution :
Just change the before_save callback into a before_validation callback.