require_dependency 'notification_levels' class CategoryUser < ActiveRecord::Base belongs_to :category belongs_to :user def self.lookup(user, level) self.where(user: user, notification_level: notification_levels[level]) end def self.lookup_by_category(user, category) self.where(user: user, category: category) end def self.notification_levels NotificationLevels.all end def self.watching_levels [notification_levels[:watching], notification_levels[:watching_first_post]] end def self.batch_set(user, level, category_ids) records = CategoryUser.where(user: user, notification_level: notification_levels[level]) old_ids = records.pluck(:category_id) changed = false category_ids = Category.where('id in (?)', category_ids).pluck(:id) remove = (old_ids - category_ids) if remove.present? records.where('category_id in (?)', remove).destroy_all changed = true end (category_ids - old_ids).each do |id| CategoryUser.create!(user: user, category_id: id, notification_level: notification_levels[level]) changed = true end if changed auto_watch(user_id: user.id) auto_track(user_id: user.id) end changed end def self.set_notification_level_for_category(user, level, category_id) record = CategoryUser.where(user: user, category_id: category_id).first return if record && record.notification_level == level if record.present? record.notification_level = level record.save! else CategoryUser.create!(user: user, category_id: category_id, notification_level: level) end auto_watch(user_id: user.id) auto_track(user_id: user.id) end def self.auto_track(opts={}) builder = SqlBuilder.new <