日期:2014-05-16 浏览次数:20505 次
using validates :email, :uniqueness => true?
?
doesn't guarantee uniqueness!!!!!
?
here is why:
?
1. Alice sign up with address alice@wonderland.com
2. Alice accidentally clicks on "Submit" twice, sending two requests in quick succession.
3. the following sequence occurs: ?request 1 creat a user in memory that passes validation, request 2 does the same, request 1's user gets saved, request 2's user gets saved.
4. two records with same email address in database.
?
this will probably happen in a scaling server.
?
how to solve it????
?
easy, you just need to enforce uniqueness at the database level!!!
our method is to creste database index on the eamil column, and then require that the index be unique!!
?
so we need to update our data model using a new migration,?
?
rails generate migration add_email_uniqueness_index
?
this will creste an empty file, we need to fill in it:
?
?
class AddEmailUniquenessIndex < ActiveRecord::Migration def self.up add_index :users, :email, :unique => true end def self.down remove_index :users, :email end end
?
then rake db:migrate
?
(adding index not only solve the uniqueness problem, it also solve another efficiency problem:
when searching by email column
find_by_email("abcd@abcd.com")
?
)
?