Skip to content

Instantly share code, notes, and snippets.

@flarnie
Created August 17, 2013 14:14
Show Gist options
  • Save flarnie/6257056 to your computer and use it in GitHub Desktop.
Save flarnie/6257056 to your computer and use it in GitHub Desktop.
The right way to validate uniqueness case insensitive of email in Ruby on Rails.
##Check uniqueness of email-----------------------------------------------
#in migration
add_index :users, :email, :unique => true
#but that doesn't cover case insensitive
#in the model take email to lowercase before save
class User..
attr_accessible :email
#this gives you custom message for the error
validates :email => uniqueness => { :message => "is a duplicate" }
#this is the callback
before_validate :normalize_emailß
def normalize_email
self.email = self.email.downcase.strip
end
#an even better way
def email=(email)
super(email.downcase.strip)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment