Improve UserEmail#email validation to use the index.

This commit is contained in:
Guo Xiang Tan 2018-03-20 10:22:06 +08:00
parent 42e49f6c7b
commit 69a53210d3
2 changed files with 22 additions and 4 deletions

View File

@ -7,14 +7,13 @@ class UserEmail < ActiveRecord::Base
before_validation :strip_downcase_email
validates :email, presence: true, uniqueness: true
validates :email, presence: true
validates :email, email: true, format: { with: EmailValidator.email_regex },
if: :validate_email?
validates :primary, uniqueness: { scope: [:user_id] }, if: :user_id
validate :user_id_not_changed, if: :primary
validates :primary, uniqueness: { scope: [:user_id] }
validate :unique_email
private
@ -30,6 +29,12 @@ class UserEmail < ActiveRecord::Base
email_changed?
end
def unique_email
if self.will_save_change_to_email? && self.class.where("lower(email) = ?", email).exists?
self.errors.add(:email, :taken)
end
end
def user_id_not_changed
if self.will_save_change_to_user_id? && self.persisted?
self.errors.add(:user_id, I18n.t(

View File

@ -28,6 +28,19 @@ describe User do
end
end
describe 'when record has an email that as already been taken' do
it 'should not be valid' do
user2 = Fabricate(:user)
user.email = user2.email.upcase
expect(user).to_not be_valid
expect(user.errors.messages[:primary_email]).to include(I18n.t(
'activerecord.errors.messages.taken'
))
end
end
describe 'when user is staged' do
it 'should still validate presence of primary_email' do
user.staged = true