From 195982fd41289051c266d5a3926ef51bf1ac1d40 Mon Sep 17 00:00:00 2001 From: Guo Xiang Tan Date: Thu, 14 Sep 2017 12:07:35 +0800 Subject: [PATCH] PERF: Remove N+1 query when generating posters summary. --- lib/primary_group_lookup.rb | 4 +++- lib/topic_query.rb | 7 ++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/primary_group_lookup.rb b/lib/primary_group_lookup.rb index 5f488dfedf9..ad3b4a5e01c 100644 --- a/lib/primary_group_lookup.rb +++ b/lib/primary_group_lookup.rb @@ -24,7 +24,9 @@ class PrimaryGroupLookup .select(:id, :primary_group_id) group_lookup = {} - group_ids = users_with_primary_group.map(&:primary_group_id).compact + group_ids = users_with_primary_group.map(&:primary_group_id) + group_ids.uniq! + Group.where(id: group_ids).select(self.class.lookup_columns) .each { |g| group_lookup[g.id] = g } diff --git a/lib/topic_query.rb b/lib/topic_query.rb index 2e99ca16d4c..98882bc866e 100644 --- a/lib/topic_query.rb +++ b/lib/topic_query.rb @@ -346,8 +346,13 @@ class TopicQuery end avatar_lookup = AvatarLookup.new(user_ids) + primary_group_lookup = PrimaryGroupLookup.new(user_ids) + topics.each do |t| - t.posters = t.posters_summary(avatar_lookup: avatar_lookup) + t.posters = t.posters_summary( + avatar_lookup: avatar_lookup, + primary_group_lookup: primary_group_lookup + ) end end