2019-05-02 17:17:27 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2014-03-05 06:52:20 -06:00
|
|
|
class UserBadge < ActiveRecord::Base
|
|
|
|
belongs_to :badge
|
|
|
|
belongs_to :user
|
|
|
|
belongs_to :granted_by, class_name: 'User'
|
2014-06-17 00:59:28 -05:00
|
|
|
belongs_to :notification, dependent: :destroy
|
2014-06-27 14:08:03 -05:00
|
|
|
belongs_to :post
|
2014-03-05 06:52:20 -06:00
|
|
|
|
2017-08-30 23:06:56 -05:00
|
|
|
validates :badge_id,
|
|
|
|
presence: true,
|
|
|
|
uniqueness: { scope: :user_id },
|
|
|
|
if: :single_grant_badge?
|
|
|
|
|
2014-03-05 06:52:20 -06:00
|
|
|
validates :user_id, presence: true
|
|
|
|
validates :granted_at, presence: true
|
|
|
|
validates :granted_by, presence: true
|
2014-06-17 10:11:52 -05:00
|
|
|
|
|
|
|
after_create do
|
|
|
|
Badge.increment_counter 'grant_count', self.badge_id
|
2015-02-25 18:50:58 -06:00
|
|
|
DiscourseEvent.trigger(:user_badge_granted, self.badge_id, self.user_id)
|
2014-06-17 10:11:52 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
after_destroy do
|
|
|
|
Badge.decrement_counter 'grant_count', self.badge_id
|
2015-02-25 18:50:58 -06:00
|
|
|
DiscourseEvent.trigger(:user_badge_removed, self.badge_id, self.user_id)
|
2014-06-17 10:11:52 -05:00
|
|
|
end
|
2017-08-30 23:06:56 -05:00
|
|
|
|
|
|
|
private
|
|
|
|
|
2018-06-07 00:28:18 -05:00
|
|
|
def single_grant_badge?
|
2019-04-23 05:25:21 -05:00
|
|
|
self.badge ? self.badge.single_grant? : true
|
2018-06-07 00:28:18 -05:00
|
|
|
end
|
2014-03-05 06:52:20 -06:00
|
|
|
end
|
|
|
|
|
|
|
|
# == Schema Information
|
|
|
|
#
|
|
|
|
# Table name: user_badges
|
|
|
|
#
|
2014-06-17 00:59:28 -05:00
|
|
|
# id :integer not null, primary key
|
|
|
|
# badge_id :integer not null
|
|
|
|
# user_id :integer not null
|
|
|
|
# granted_at :datetime not null
|
|
|
|
# granted_by_id :integer not null
|
|
|
|
# post_id :integer
|
|
|
|
# notification_id :integer
|
2014-08-10 18:21:06 -05:00
|
|
|
# seq :integer default(0), not null
|
2014-03-05 06:52:20 -06:00
|
|
|
#
|
|
|
|
# Indexes
|
|
|
|
#
|
2014-07-14 20:29:44 -05:00
|
|
|
# index_user_badges_on_badge_id_and_user_id (badge_id,user_id)
|
2018-07-16 01:18:07 -05:00
|
|
|
# index_user_badges_on_badge_id_and_user_id_and_post_id (badge_id,user_id,post_id) UNIQUE WHERE (post_id IS NOT NULL)
|
|
|
|
# index_user_badges_on_badge_id_and_user_id_and_seq (badge_id,user_id,seq) UNIQUE WHERE (post_id IS NULL)
|
2019-01-11 13:29:56 -06:00
|
|
|
# index_user_badges_on_user_id (user_id)
|
2014-03-05 06:52:20 -06:00
|
|
|
#
|