PERF: cache category topic ids

This commit is contained in:
Sam 2016-07-19 12:34:54 +10:00
parent c1a01b2a28
commit 1c964bf730
3 changed files with 17 additions and 2 deletions

View File

@ -61,6 +61,9 @@ class Category < ActiveRecord::Base
has_many :category_tag_groups, dependent: :destroy has_many :category_tag_groups, dependent: :destroy
has_many :tag_groups, through: :category_tag_groups 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 :latest, -> { order('topic_count DESC') }
scope :secured, -> (guardian = nil) { scope :secured, -> (guardian = nil) {
@ -83,6 +86,18 @@ class Category < ActiveRecord::Base
# we may consider wrapping this in another spot # we may consider wrapping this in another spot
attr_accessor :displayable_topics, :permission, :subcategory_ids, :notification_level, :has_children 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 def self.last_updated_at
order('updated_at desc').limit(1).pluck(:updated_at).first.to_i order('updated_at desc').limit(1).pluck(:updated_at).first.to_i
end end

View File

@ -7,7 +7,7 @@ class SuggestedTopicsBuilder
def initialize(topic) def initialize(topic)
@excluded_topic_ids = [topic.id] @excluded_topic_ids = [topic.id]
@category_id = topic.category_id @category_id = topic.category_id
@category_topic_ids = Category.pluck(:topic_id).compact @category_topic_ids = Category.topic_ids
@results = [] @results = []
end end

View File

@ -699,7 +699,7 @@ class TopicQuery
def random_suggested(topic, count, excluded_topic_ids=[]) def random_suggested(topic, count, excluded_topic_ids=[])
result = default_results(unordered: true, per_page: count).where(closed: false, archived: false) 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 = result.where("topics.id NOT IN (?)", excluded_topic_ids) unless excluded_topic_ids.empty?
result = remove_muted_categories(result, @user) result = remove_muted_categories(result, @user)