【发布时间】:2012-03-11 20:26:15
【问题描述】:
我一直在关注本教程http://ruby.railstutorial.org/chapters/modeling-users?version=3.2#top,我觉得这很好,但它提到了一些我没有得到的关于唯一性属性的内容。 到目前为止,这是 mu 用户文件:
class User < ActiveRecord::Base
#these attributes can be modified by the users
attr_accessible :name, :email;
#validation testing
validates :name, presence: true, length: { maximum: 50 }
#regular expression (there is an official one)
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
#and add it..
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
end
上面写着:
" 使用 validates :uniqueness 并不能保证唯一性。
Alice 不小心点击了两次“提交”,快速连续发送了两个请求。 以下顺序发生:请求 1 在内存中创建一个通过验证的用户,请求 2 执行相同操作,请求 1 的用户被保存,请求 2 的用户被保存。 结果:尽管进行了唯一性验证,但两个用户记录具有完全相同的电子邮件地址。”
我尝试使用控制台(和 User.create 方法)创建 2 个具有相同电子邮件地址的用户,并且唯一性似乎工作正常,因为只有第一个用户进入了 sqlite3。那么什么会导致错误或唯一性失败呢?
【问题讨论】:
标签: ruby-on-rails