我在Rails 3.1.1应用程序中有以下类:
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :admin, :moderator, :bio
validates_presence_of :username
validates_uniqueness_of :username, :case_sensitive => false
validates_uniqueness_of :email, :case_sensitive => false
和我的迁移:
add_index :users, :email, :unique => true
add_index :users, :username, :unique => true
然而,当我尝试创建两个具有重复电子邮件或用户名的用户时,我得到一个DB级异常,而不是失败的验证:
ActiveRecord::RecordNotUnique in RegistrationsController#create
PGError: ERROR: duplicate key value violates unique constraint "index_users_on_username"
有其他的验证工作完美,但为什么不唯一性验证在数据库创建之前执行?
试试这样:
class User < ActiveRecord::Base
attr_accessible :email,
:password,
:password_confirmation,
:remember_me,
:username,
:admin,
:moderator,
:bio
validates :username, :uniqueness => { :case_sensitive => false }, :presence => true
validates :email, :uniqueness => { :case_sensitive => false }