Home > Software design >  Rails validations on create and update methods
Rails validations on create and update methods

Time:10-21

So i have the following scenario. I want to create a new User but i want it's email to be unique. So i have the following validation


  def uniq_email
    errors.add(:email, "Already existing User with email: #{email}") if
      User.exists?(email: email)
  end

This works good. The problem is when i want to update this user, if i try to change the email with an already existing one it allows me to do that. I tried adding [:create, :update] in validation but if i do this, when i change it's address for example it runs again the validation on the model and tells me that user with that email already exists. Any help? How can i avoid this?

Thank you :D

CodePudding user response:

The best solution for your scenario is to use validates_uniqueness_of or uniqueness as it ensures the email uniqueness at the application level.

class User < ActiveRecord::Base
  validates_uniqueness_of :email
  # or
  validates :email, uniqueness: true
end

To make the uniqueness bulletproof, a unique index on email should be added in the db. If, for some reason, you bypass the validations in the model, the DB will raise an error.

class MakeEmailUnique < ActiveRecord::Migration
  def change
    add_index :users, :email, unique: true
  end
end

You should go over the Validation Docs docs to learn more about how to use them.

  • Related