A platform for community discussion. Free, open, simple.
DEV: Properly support composing multiple category filters on `/filter` (#20953)
Alan Guo Xiang Tan62696b9ee7c0
diff --git a/lib/topics_filter.rb b/lib/topics_filter.rbindex 20ec17ef0c9..84cd147aacf 100644--- a/lib/topics_filter.rb+++ b/lib/topics_filter.rb@@ -8,6 +8,7 @@ class TopicsFilterdef filter_from_query_string(query_string)return @scope if query_string.blank?+ category_or_clause = falsequery_string.scan(/(?<key_prefix>[-=])?(?<key>\w+):(?<value>[^\s]+)/,@@ -45,7 +46,10 @@ class TopicsFilterfilter_categories(category_slugs: category_slugs.split(delimiter),exclude_subcategories: key_prefix.presence,+ or_clause: category_or_clause,)++ category_or_clause = trueendendend@@ -80,7 +84,7 @@ class TopicsFilterprivate- def filter_categories(category_slugs:, exclude_subcategories: false)+ def filter_categories(category_slugs:, exclude_subcategories: false, or_clause: false)category_ids = Category.ids_from_slugs(category_slugs)category_ids =@@ -96,7 +100,11 @@ class TopicsFiltercategory_ids = category_ids.flat_map { |category_id| Category.subcategory_ids(category_id) }end- @scope = @scope.joins(:category).where("categories.id IN (?)", category_ids)+ if or_clause+ @scope.or(Topic.where("categories.id IN (?)", category_ids))+ else+ @scope.joins(:category).where("categories.id IN (?)", category_ids)+ endenddef filter_tags(tag_names:, match_all: true, exclude: false)diff --git a/spec/lib/topics_filter_spec.rb b/spec/lib/topics_filter_spec.rbindex 80ae4b0a304..fa0c55f9db2 100644--- a/spec/lib/topics_filter_spec.rb+++ b/spec/lib/topics_filter_spec.rb@@ -138,6 +138,37 @@ RSpec.describe TopicsFilter doendend+ describe "when query string is `category:category category:category2`" do+ it "should return topics from any of the specified categories and its subcategories" do+ expect(+ TopicsFilter+ .new(guardian: Guardian.new)+ .filter_from_query_string("category:category category:category2")+ .pluck(:id),+ ).to contain_exactly(+ topic_in_category.id,+ topic_in_category_subcategory.id,+ topic_in_category2.id,+ topic_in_category2_subcategory.id,+ )+ end+ end++ describe "when query string is `category:category =category:category2`" do+ it "should return topics and subcategory topics from category but only topics from category2" do+ expect(+ TopicsFilter+ .new(guardian: Guardian.new)+ .filter_from_query_string("category:category =category:category2")+ .pluck(:id),+ ).to contain_exactly(+ topic_in_category.id,+ topic_in_category_subcategory.id,+ topic_in_category2.id,+ )+ end+ end+describe "when query string is `=category:category`" doit "should not return topics from subcategories`" doexpect(