notification_request.rb 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: notification_requests
  5. #
  6. # id :bigint(8) not null, primary key
  7. # account_id :bigint(8) not null
  8. # from_account_id :bigint(8) not null
  9. # last_status_id :bigint(8)
  10. # notifications_count :bigint(8) default(0), not null
  11. # created_at :datetime not null
  12. # updated_at :datetime not null
  13. #
  14. class NotificationRequest < ApplicationRecord
  15. self.ignored_columns += %w(dismissed)
  16. include Paginable
  17. MAX_MEANINGFUL_COUNT = 100
  18. belongs_to :account
  19. belongs_to :from_account, class_name: 'Account'
  20. belongs_to :last_status, class_name: 'Status'
  21. before_save :prepare_notifications_count
  22. scope :without_suspended, -> { joins(:from_account).merge(Account.without_suspended) }
  23. def self.preload_cache_collection(requests)
  24. cached_statuses_by_id = yield(requests.filter_map(&:last_status)).index_by(&:id) # Call cache_collection in block
  25. requests.each do |request|
  26. request.last_status = cached_statuses_by_id[request.last_status_id] unless request.last_status_id.nil?
  27. end
  28. end
  29. def reconsider_existence!
  30. prepare_notifications_count
  31. if notifications_count.positive?
  32. save
  33. else
  34. destroy
  35. end
  36. end
  37. private
  38. def prepare_notifications_count
  39. self.notifications_count = Notification.where(account: account, from_account: from_account, type: :mention, filtered: true).limit(MAX_MEANINGFUL_COUNT).count
  40. end
  41. end