首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > 其他数据库 >

6.2 the uniqueness caveat when saving into database: adding index to tables!

2012-10-09 
6.2 the uniqueness caveat when saving into database: adding index to tables!!!using validates :emai

6.2 the uniqueness caveat when saving into database: adding index to tables!!!

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  endend

?

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")

?

)

?

热点排行