From 884779b5c18f1b963e532d904198df7e00cf9dda Mon Sep 17 00:00:00 2001 From: Neil Lalonde Date: Thu, 26 May 2016 18:03:36 -0400 Subject: [PATCH] FIX: N+1 query when tagging enabled and no tags in topic list query. Topic query ignored tags input when tagging is disabled. --- lib/topic_query.rb | 18 +++++++++++------- spec/components/topic_query_spec.rb | 4 ++++ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/lib/topic_query.rb b/lib/topic_query.rb index 65696d64c..d2add0c9b 100644 --- a/lib/topic_query.rb +++ b/lib/topic_query.rb @@ -455,14 +455,18 @@ class TopicQuery # ALL TAGS: something like this? # Topic.joins(:tags).where('tags.name in (?)', @options[:tags]).group('topic_id').having('count(*)=?', @options[:tags].size).select('topic_id') - if @options[:tags] && @options[:tags].size > 0 - result = result.joins(:tags).preload(:tags) + if SiteSetting.tagging_enabled + result = result.preload(:tags) - # ANY of the given tags: - if @options[:tags][0].is_a?(Integer) - result = result.where("tags.id in (?)", @options[:tags]) - else - result = result.where("tags.name in (?)", @options[:tags]) + if @options[:tags] && @options[:tags].size > 0 + result = result.joins(:tags) + + # ANY of the given tags: + if @options[:tags][0].is_a?(Integer) + result = result.where("tags.id in (?)", @options[:tags]) + else + result = result.where("tags.name in (?)", @options[:tags]) + end end end diff --git a/spec/components/topic_query_spec.rb b/spec/components/topic_query_spec.rb index 663fdef53..d3298a9dc 100644 --- a/spec/components/topic_query_spec.rb +++ b/spec/components/topic_query_spec.rb @@ -118,6 +118,10 @@ describe TopicQuery do let(:tag) { Fabricate(:tag) } let(:other_tag) { Fabricate(:tag) } + before do + SiteSetting.tagging_enabled = true + end + it "returns topics with the tag when filtered to it" do tagged_topic1 = Fabricate(:topic, {tags: [tag]}) tagged_topic2 = Fabricate(:topic, {tags: [other_tag]})