Skip to content

Instantly share code, notes, and snippets.

@mskyle
Last active December 24, 2015 13:09
Show Gist options
  • Save mskyle/6803154 to your computer and use it in GitHub Desktop.
Save mskyle/6803154 to your computer and use it in GitHub Desktop.
validates presence of either email or username?
validate :has_unique_email_or_username, on: :create
def has_unique_email_or_username
if username.nil? && email.nil?
errors.add(:email, "valid email or username required")
elsif not email.match(/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/)
errors.add(:email, "please enter a valid email")
elsif User.where(email: email).count > 0
errors.add(:email, "that email has already been taken")
elsif User.where(username: username).count > 0
errors.add(:username, "that username has already been taken")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment