ActiveRecord::RecordNotUnique 之前的 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"
还有其他有效的验证完美,但是为什么在创建数据库之前不执行唯一性验证?
I have the following class in a Rails 3.1.1 app:
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
and in my migrations:
add_index :users, :email, :unique => true
add_index :users, :username, :unique => true
However, when I try to create two users with duplicate emails or usernames I get a DB level exception rather than a failing validation:
ActiveRecord::RecordNotUnique in RegistrationsController#create
PGError: ERROR: duplicate key value violates unique constraint "index_users_on_username"
There are other validations that work perfectly, but why aren't the uniqueness validations being performed before the DB create?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试这样的事情:
Try something like this: