Eren CAY
Eren CAY

Reputation: 696

Validate uniqueness for multiple columns individually

I have a user model with username and nickname fields. What I want to do is to create a validations rule that can check uniqueness for both fields individually, not as a combination (or scope I think).

Upvotes: 0

Views: 138

Answers (2)

moritz
moritz

Reputation: 25757

What about

validate do |r|
  if where("username LIKE ? OR nickname LIKE ?", r.username, r.username).first
    r.errors.add :username, "is already taken"
  end

  if where("username LIKE ? OR nickname LIKE ?", r.nickname, r.nickname).first
    r.errors.add :nickname, "is already taken"
  end
end

Upvotes: 1

Catfish
Catfish

Reputation: 19284

Can't you just do this?

validates :username, :uniqueness => true
validates :nickname, :uniqueness => true

Upvotes: 0

Related Questions