Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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