Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby User Authentication with Rails Password Hashing and Sign In Creating the User model: Part 2

Is it better to use "before_validation" instead of "before_save"?

In models/user.rb, this line of codes was written by Jason:

before_save :downcase_email

It will downcase the email attribute before saving but not before validating, which means if you wanna validate the uniqueness of email case-insensitively, "EXAMPLE@EXAMPLE.COM" will be validated as unique because there will be only "example@example.com" in database.

I have tried before_validation:

before_validation :downcase_email

Now it works for me to check the uniqueness of email case-insensitively using shoulda-matchers:

it { should validate_uniqueness_of(:email).case_insensitive }

And if the input of email is "EXAMPLE@EXAMPLE.COM" after saving a same one, it will show the error of non-uniqueness.

Another way I just found out:

validates :email, presence: true, uniqueness: { case_sensitive: false }

before_save :downcase_email