diff --git a/app/models/category.rb b/app/models/category.rb index 3ad7d5b5123..b9f30b26b6a 100644 --- a/app/models/category.rb +++ b/app/models/category.rb @@ -61,6 +61,9 @@ class Category < ActiveRecord::Base has_many :category_tag_groups, dependent: :destroy has_many :tag_groups, through: :category_tag_groups + after_save :clear_topic_ids_cache + after_destroy :clear_topic_ids_cache + scope :latest, -> { order('topic_count DESC') } scope :secured, -> (guardian = nil) { @@ -83,6 +86,18 @@ class Category < ActiveRecord::Base # we may consider wrapping this in another spot attr_accessor :displayable_topics, :permission, :subcategory_ids, :notification_level, :has_children + def self.topic_ids + @topic_ids ||= Set.new(Category.pluck(:topic_id).compact) + end + + def self.clear_topic_ids_cache + @topic_ids = nil + end + + def clear_topic_ids_cache + Category.clear_topic_ids_cache + end + def self.last_updated_at order('updated_at desc').limit(1).pluck(:updated_at).first.to_i end diff --git a/lib/suggested_topics_builder.rb b/lib/suggested_topics_builder.rb index 33dc6007083..9436bb5c5a9 100644 --- a/lib/suggested_topics_builder.rb +++ b/lib/suggested_topics_builder.rb @@ -7,7 +7,7 @@ class SuggestedTopicsBuilder def initialize(topic) @excluded_topic_ids = [topic.id] @category_id = topic.category_id - @category_topic_ids = Category.pluck(:topic_id).compact + @category_topic_ids = Category.topic_ids @results = [] end diff --git a/lib/topic_query.rb b/lib/topic_query.rb index 81ef8e0a05b..ed4aecf8181 100644 --- a/lib/topic_query.rb +++ b/lib/topic_query.rb @@ -699,7 +699,7 @@ class TopicQuery def random_suggested(topic, count, excluded_topic_ids=[]) result = default_results(unordered: true, per_page: count).where(closed: false, archived: false) - excluded_topic_ids += Category.pluck(:topic_id).compact + excluded_topic_ids += Category.topic_ids.to_a result = result.where("topics.id NOT IN (?)", excluded_topic_ids) unless excluded_topic_ids.empty? result = remove_muted_categories(result, @user)