DEV: Improve User#email= behavior (#11338)

- Only apply the change after `save` is called on the record
- Automatically remove matching secondary emails
This commit is contained in:
David Taylor
2021-02-22 11:42:37 +00:00
committed by GitHub
parent 74d83abcc7
commit ef19431e44
3 changed files with 50 additions and 6 deletions

View File

@@ -4,6 +4,7 @@ class UserEmail < ActiveRecord::Base
belongs_to :user
attr_accessor :skip_validate_email
attr_accessor :skip_validate_unique_email
before_validation :strip_downcase_email
@@ -12,7 +13,7 @@ class UserEmail < ActiveRecord::Base
validates :primary, uniqueness: { scope: [:user_id] }, if: [:user_id, :primary]
validate :user_id_not_changed, if: :primary
validate :unique_email
validate :unique_email, if: :validate_unique_email?
scope :secondary, -> { where(primary: false) }
@@ -30,8 +31,13 @@ class UserEmail < ActiveRecord::Base
email_changed?
end
def validate_unique_email?
return false if self.skip_validate_unique_email
will_save_change_to_email?
end
def unique_email
if self.will_save_change_to_email? && self.class.where("lower(email) = ?", email).exists?
if self.class.where("lower(email) = ?", email).exists?
self.errors.add(:email, :taken)
end
end