Ruby On Rails Classroom image

Neha  Jaggi / Professional / Web Technology

To post your Question Join Classroom
Lesson Topics's No:-  |1 | 2 | 3|Last
Lessons:-Uniqueness Validation

Uniqueness Validation

To enforce uniqueness of email addresses (so that we can use them as usernames), we’ll be using the :unique option to the validates method. But be warned: There’s a major caveat, so don’t just skim this section—read it carefully.

                         We’ll start, as usual, with our tests. In our previous model tests, we’ve mainly used, which just creates a Ruby object in memory, but for uniqueness tests we actually need to put a record into the database.13 The (first) duplicate email test appears in Listing 6.18.



The method here is to make a user with the same email address as @user, which we accomplish using @user.dup, which creates a duplicate user with the same attributes. Since we then save that user, the original @user has an email address that already exists in the database, and hence should not be valid.

We can get the new test in Listing 6.18 to pass with the code in Listing 6.19



We’re not quite done, though. Email addresses are case-insensitive— goes to the same place as FOO@BAR.COM or FoO@BAr.coM—so our validation should cover this case as well. We test for this with the code in Listing 6.20.



Here we are using the upcase method on strings (seen briefly in Section 4.3.2). This test does the same thing as the first duplicate email test, but with an upper-case email address instead. If this test feels a little abstract, go ahead and fire up the console:

Neha  Jaggi

Skills    Ruby On Rails

Qualifications :- High School - , College/University - Graphic Era Hill University, Dehradun, College/University - ,
Location :-Dehradun,Dehradun,UTTARAKHAND,India

Experienced Software Developer with a demonstrated history of working in the Information Technology and services industry. Skilled in Web Technologies (Ruby on Rails, PostgreSQL, php, Laravel and AJAX). 


  Students (0)