From 543e972fec7637a709032c49bc13d5cc91a80d21 Mon Sep 17 00:00:00 2001 From: Guo Xiang Tan Date: Fri, 11 Sep 2020 16:26:04 +0800 Subject: [PATCH] PERF: Remove category_user lookup when loading private messages. Private messages do not belong to categories so the query is unnecessary overhead. --- app/models/topic_list.rb | 18 ++++++++++++++++-- spec/models/topic_list_spec.rb | 10 ++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/app/models/topic_list.rb b/app/models/topic_list.rb index 7dca12800c3..8ab04925807 100644 --- a/app/models/topic_list.rb +++ b/app/models/topic_list.rb @@ -80,7 +80,6 @@ class TopicList < DraftableList # Attach some data for serialization to each topic @topic_lookup = TopicUser.lookup_for(@current_user, @topics) if @current_user - @category_user_lookup = CategoryUser.lookup_for(@current_user, @topics.map(&:category_id).uniq) if @current_user post_action_type = if @current_user @@ -111,7 +110,10 @@ class TopicList < DraftableList @topics.each do |ft| ft.user_data = @topic_lookup[ft.id] if @topic_lookup.present? - ft.category_user_data = @category_user_lookup[ft.category_id] if @category_user_lookup.present? + + if ft.regular? && category_user_lookup.present? + ft.category_user_data = @category_user_lookup[ft.category_id] + end if ft.user_data && post_action_lookup && actions = post_action_lookup[ft.id] ft.user_data.post_action_data = { post_action_type => actions } @@ -140,4 +142,16 @@ class TopicList < DraftableList def attributes { 'more_topics_url' => page } end + + private + + def category_user_lookup + @category_user_lookup ||= begin + if @current_user + CategoryUser.lookup_for(@current_user, @topics.map(&:category_id).uniq) + else + [] + end + end + end end diff --git a/spec/models/topic_list_spec.rb b/spec/models/topic_list_spec.rb index fb4265d0ce0..fbf27ac9017 100644 --- a/spec/models/topic_list_spec.rb +++ b/spec/models/topic_list_spec.rb @@ -48,6 +48,16 @@ describe TopicList do end end + describe '#load_topics' do + it 'loads additional data for serialization' do + category_user = CategoryUser.create!(user: user, category: topic.category) + + topic = topic_list.load_topics.first + + expect(topic.category_user_data).to eq(category_user) + end + end + describe '#top_tags' do it 'should return the right tags' do tag = Fabricate(:tag, topics: [topic])