Theo Pearson-Bray Theo Pearson-Bray - 1 year ago 84
Ruby Question

How can I cross validate the uniqueness of two columns, username and email

I have a user model with a username and email. Currently, the email is used to log in, however I want users to be able to log in with their username as well. In order to do this, I have to ensure that one users username is not the same as another's email, and vice versa.

My uniqueness validations for each individual field work fine, but I can't get validation across the columns to work.

My validations are as follows:

validates(:username, presence: true, length: { maximum: 25 }, uniqueness: {case_sensitive: false })
validates(:username, uniqueness: {scope: :email, case_sensitive: false});


validates(:email, presence: true, length: { maximum: 255 },
format: {with: VALIDATE_EMAIL_REGEX}, uniqueness: { case_sensitive: false })
validates(:email, uniqueness: {scope: :username, case_sensitive: false})

How can I validate the uniqueness of these two columns?
Any help is appreciated.

Answer Source

How can I validate the uniqueness of these two columns?

You could write a custom validation method:

validate :uniq_username_and_email


def uniq_username_and_email
  self.errors.add(:username, 'already taken') if User.exists?(email: username)
  self.errors.add(:email, 'already taken') if User.exists?(username: email)

Assuming that your model is named User

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download