Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to validate uniqueness of field before save, if field is changed before save?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just change the before_save callback into a before_validation callback.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading