Ruby On Rails Classroom image

Pooja  Negi / Student / Web Technology

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

of this, take a look at the file db/schema.rb, which should now include a line like this:

add index  "users",  [ "email" ], :name =>  "index users on email", :unique =>  true

 

Unfortunately, there’s one more change we need to make to be assured of email uniqueness, which is to make sure that the email address is all lowercase before it gets saved to the database. The reason is that not all database adapters use case-sensitive indices.15 The way to do this is with a callback, which is a method that gets invoked at a particular point in the lifetime of an Active Record object (see the Rails API entry on callbacks). In the present case, we’ll use a before_save callback to force Rails to downcase the email attribute before saving the user to the database, as shown in Listing 6.23.  

 

 

The code in Listing 6.23 passes a block to the before_save callback and sets the user’s email address to a lowercase version of its current value using the downcase string method. This code is a little advanced, and at this point I suggest you simply trust that it works; if you’re skeptical, comment out the uniqueness validation from Listing 6.19 and try to create users with identical email addresses to see the error that results. (We’ll see this technique again in Section 8.2.1.)

Now the Alice scenario above will work fine: The database will save a user record based on the first request and will reject the second save for violating the uniqueness constraint. (An error will appear in the Rails log, but that doesn’t do any harm. You can actually catch the ActiveRecord::StatementInvalid exception that gets raised—see Insoshi for an example—but in this tutorial we won’t bother with this step.) Adding this index on the email attribute accomplishes a second goal, alluded to briefly in Section 6.1.4: It fixes an efficiency problem in find_by_email (Box 6.2).

 

 
 
 
image
Pooja   Negi

Skills    Ruby On Rails

Qualifications :- High School - SSN high school, College/University - HNBGU, College/University - SRHU,
Location :-Ranipokhari,Rishikesh,Uttarakhand,India
Description:- Student
Explore
 

  Students (0)