Skip to content

A platform for community discussion. Free, open, simple.

DEV: Fix `TopcisFilter#filter_tags` not working for a single tag (#20840)

Alan Guo Xiang Tan4624cca00fe0
diff --git a/lib/topics_filter.rb b/lib/topics_filter.rb
index c5fc97eed50..c52c74ac0e7 100644
--- a/lib/topics_filter.rb
+++ b/lib/topics_filter.rb
@@ -74,10 +74,10 @@ class TopicsFilter
def exclude_topics_with_any_tags(tag_ids)
@scope =
- @scope
- .left_joins(:topic_tags)
- .where("topic_tags.tag_id IS NULL OR topic_tags.tag_id NOT IN (?)", tag_ids)
- .distinct(:id)
+ @scope.where(
+ "topics.id NOT IN (SELECT DISTINCT topic_id FROM topic_tags WHERE topic_tags.tag_id IN (?))",
+ tag_ids,
+ )
end
def include_topics_with_all_tags(tag_ids)
diff --git a/spec/lib/topics_filter_spec.rb b/spec/lib/topics_filter_spec.rb
index 3779d4fee09..488832d0ea1 100644
--- a/spec/lib/topics_filter_spec.rb
+++ b/spec/lib/topics_filter_spec.rb
@@ -153,6 +153,13 @@ RSpec.describe TopicsFilter do
end
it "should only return topics that are not tagged with all of the specified tags when `match_all` is `true` and `exclude` is `true`" do
+ expect(
+ TopicsFilter
+ .new(guardian: Guardian.new)
+ .filter_tags(tag_names: [tag.name], match_all: true, exclude: true)
+ .pluck(:id),
+ ).to contain_exactly(topic_without_tag.id, topic_with_tag2.id, topic_with_group_only_tag.id)
+
expect(
TopicsFilter
.new(guardian: Guardian.new)
@@ -167,6 +174,13 @@ RSpec.describe TopicsFilter do
end
it "should only return topics that are not tagged with any of the specified tags when `match_all` is `false` and `exclude` is `true`" do
+ expect(
+ TopicsFilter
+ .new(guardian: Guardian.new)
+ .filter_tags(tag_names: [tag.name], match_all: false, exclude: true)
+ .pluck(:id),
+ ).to contain_exactly(topic_without_tag.id, topic_with_group_only_tag.id, topic_with_tag2.id)
+
expect(
TopicsFilter
.new(guardian: Guardian.new)