You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.6 KiB

  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: featured_tags
  5. #
  6. # id :bigint(8) not null, primary key
  7. # account_id :bigint(8)
  8. # tag_id :bigint(8)
  9. # statuses_count :bigint(8) default(0), not null
  10. # last_status_at :datetime
  11. # created_at :datetime not null
  12. # updated_at :datetime not null
  13. #
  14. class FeaturedTag < ApplicationRecord
  15. belongs_to :account, inverse_of: :featured_tags, required: true
  16. belongs_to :tag, inverse_of: :featured_tags, required: true
  17. delegate :name, to: :tag, allow_nil: true
  18. validates_associated :tag, on: :create
  19. validates :name, presence: true, on: :create
  20. validate :validate_featured_tags_limit, on: :create
  21. def name=(str)
  22. self.tag = Tag.find_or_create_by_names(str.strip)&.first
  23. end
  24. def increment(timestamp)
  25. update(statuses_count: statuses_count + 1, last_status_at: timestamp)
  26. end
  27. def decrement(deleted_status_id)
  28. update(statuses_count: [0, statuses_count - 1].max, last_status_at: account.statuses.where(visibility: %i(public unlisted)).tagged_with(tag).where.not(id: deleted_status_id).select(:created_at).first&.created_at)
  29. end
  30. def reset_data
  31. self.statuses_count = account.statuses.where(visibility: %i(public unlisted)).tagged_with(tag).count
  32. self.last_status_at = account.statuses.where(visibility: %i(public unlisted)).tagged_with(tag).select(:created_at).first&.created_at
  33. end
  34. private
  35. def validate_featured_tags_limit
  36. errors.add(:base, I18n.t('featured_tags.errors.limit')) if account.featured_tags.count >= 10
  37. end
  38. end