Created
August 17, 2013 14:14
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##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