2017-04-26 14:47:36 -04:00
|
|
|
require_dependency 'email_validator'
|
|
|
|
|
|
|
|
class UserEmail < ActiveRecord::Base
|
|
|
|
belongs_to :user
|
|
|
|
|
2017-10-25 01:02:18 -04:00
|
|
|
attr_accessor :skip_validate_email
|
2017-08-08 22:56:08 -04:00
|
|
|
|
2017-04-26 14:47:36 -04:00
|
|
|
before_validation :strip_downcase_email
|
|
|
|
|
2018-03-19 22:22:06 -04:00
|
|
|
validates :email, presence: true
|
2017-04-26 14:47:36 -04:00
|
|
|
validates :email, email: true, format: { with: EmailValidator.email_regex },
|
2017-08-08 22:56:08 -04:00
|
|
|
if: :validate_email?
|
2017-04-26 14:47:36 -04:00
|
|
|
|
2017-12-21 07:30:26 -05:00
|
|
|
validates :primary, uniqueness: { scope: [:user_id] }, if: [:user_id, :primary]
|
2018-01-04 02:37:26 -05:00
|
|
|
validate :user_id_not_changed, if: :primary
|
2018-03-19 22:22:06 -04:00
|
|
|
validate :unique_email
|
2017-04-26 14:47:36 -04:00
|
|
|
|
2018-07-03 07:51:22 -04:00
|
|
|
scope :secondary, -> { where(primary: false) }
|
|
|
|
|
2017-04-26 14:47:36 -04:00
|
|
|
private
|
|
|
|
|
|
|
|
def strip_downcase_email
|
|
|
|
if self.email
|
|
|
|
self.email = self.email.strip
|
|
|
|
self.email = self.email.downcase
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2017-08-08 22:56:08 -04:00
|
|
|
def validate_email?
|
2017-10-25 01:02:18 -04:00
|
|
|
return false if self.skip_validate_email
|
2017-04-26 14:47:36 -04:00
|
|
|
email_changed?
|
|
|
|
end
|
2018-01-04 02:37:26 -05:00
|
|
|
|
2018-03-19 22:22:06 -04:00
|
|
|
def unique_email
|
|
|
|
if self.will_save_change_to_email? && self.class.where("lower(email) = ?", email).exists?
|
|
|
|
self.errors.add(:email, :taken)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2018-01-04 02:37:26 -05:00
|
|
|
def user_id_not_changed
|
|
|
|
if self.will_save_change_to_user_id? && self.persisted?
|
|
|
|
self.errors.add(:user_id, I18n.t(
|
|
|
|
'active_record.errors.model.user_email.attributes.user_id.reassigning_primary_email')
|
|
|
|
)
|
|
|
|
end
|
|
|
|
end
|
2017-04-26 14:47:36 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
# == Schema Information
|
|
|
|
#
|
|
|
|
# Table name: user_emails
|
|
|
|
#
|
|
|
|
# id :integer not null, primary key
|
|
|
|
# user_id :integer not null
|
|
|
|
# email :string(513) not null
|
|
|
|
# primary :boolean default(FALSE), not null
|
2019-01-11 14:29:56 -05:00
|
|
|
# created_at :datetime not null
|
|
|
|
# updated_at :datetime not null
|
2017-04-26 14:47:36 -04:00
|
|
|
#
|
|
|
|
# Indexes
|
|
|
|
#
|
2017-10-05 23:13:01 -04:00
|
|
|
# index_user_emails_on_email (lower((email)::text)) UNIQUE
|
2017-04-26 14:47:36 -04:00
|
|
|
# index_user_emails_on_user_id (user_id)
|
2018-07-16 02:18:07 -04:00
|
|
|
# index_user_emails_on_user_id_and_primary (user_id,primary) UNIQUE WHERE "primary"
|
2017-04-26 14:47:36 -04:00
|
|
|
#
|