Back to Course

Spot the Tax · Card 1 of 20

Uniqueness lives in the database, not in valid?

Why validates :uniqueness can't actually prevent duplicates once your traffic gets concurrent.

The code

What will this cost you in six months?

class User < ApplicationRecord
  validates :email, presence: true, uniqueness: true
end

# In the controller:
def create
  @user = User.new(user_params)
  if @user.save
    redirect_to @user
  else
    render :new
  end
end

The problem

When two users try to sign up with the same email at the exact same moment, both requests will run valid? and ask the database whether that email already exists. Since neither request has actually inserted anything yet, both checks come back clean and both saves go through. You end up with two users sharing the same email, even though the validation did exactly what it was supposed to do — it just didn't have the right vantage point to actually prevent it.

Take a moment. Before revealing, try to work out the fix yourself. Where would you put the rule? What would it look like?