summaryrefslogtreecommitdiff
path: root/app/models/email.rb
blob: 9068c2b87b632fd2645a20e315fa3fcb504ef748 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# == Schema Information
#
# Table name: emails
#
#  id         :integer          not null, primary key
#  user_id    :integer          not null
#  email      :string(255)      not null
#  created_at :datetime
#  updated_at :datetime
#

class Email < ActiveRecord::Base
  attr_accessible :email, :user_id

  #
  # Relations
  #
  belongs_to :user

  #
  # Validations
  #
  validates :user_id, presence: true
  validates :email, presence: true, email: { strict_mode: true }, uniqueness: true
  validate :unique_email, if: ->(email) { email.email_changed? }

  after_create :notify
  before_validation :cleanup_email

  def cleanup_email
    self.email = self.email.downcase.strip
  end

  def unique_email
    self.errors.add(:email, 'has already been taken') if User.exists?(email: self.email)
  end

  def notify
    NotificationService.new.new_email(self)
  end
end