validRecord :: RecordNotUnique之前的validates_uniqueness_of

时间:2011-10-15 13:13:12

标签: ruby-on-rails-3.1 validates-uniqueness-of

我在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

然而,当我尝试使用重复的电子邮件或用户名创建两个用户时,我得到了数据库级别的异常而不是失败的验证:

ActiveRecord::RecordNotUnique in RegistrationsController#create
PGError: ERROR:  duplicate key value violates unique constraint "index_users_on_username"

还有其他验证可以完美运行,但为什么在DB创建之前不执行唯一性验证?

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

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 }