validates_uniqueness_of before ActiveRecord::RecordNotUnique
-
10-02-2021 - |
Domanda
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?
Soluzione
Try something like this:
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 }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow