summaryrefslogtreecommitdiff
path: root/app/models/notification_setting.rb
blob: 846773752a67f03b6f9946e5cf23f8b40ff88fcc (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: notification_settings
#
#  id          :integer          not null, primary key
#  user_id     :integer          not null
#  source_id   :integer          not null
#  source_type :string           not null
#  level       :integer          default(0), not null
#  created_at  :datetime         not null
#  updated_at  :datetime         not null
#

class NotificationSetting < ActiveRecord::Base
  enum level: { disabled: 0,  participating: 1,  watch: 2,  global: 3, mention: 4 }

  default_value_for :level, NotificationSetting.levels[:global]

  belongs_to :user
  belongs_to :source, polymorphic: true

  validates :user, presence: true
  validates :source, presence: true
  validates :level, presence: true
  validates :user_id, uniqueness: { scope: [:source_type, :source_id],
                                    message: "already exists in source",
                                    allow_nil: true }

  scope :for_groups, -> { where(source_type: 'Namespace') }
  scope :for_projects, -> { where(source_type: 'Project') }

  def self.find_or_create_for(source)
    setting = find_or_initialize_by(source: source)

    unless setting.persisted?
      setting.save
    end

    setting
  end
end