FIX: Category results should be ordered by term (#25771)

The two criteria used to order the results are if the category name
starts with the term and if the category is a top level category or not.
This commit is contained in:
Bianca Nenciu 2024-02-21 16:32:58 +02:00 committed by GitHub
parent a9f8009801
commit d8c3924213
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 31 additions and 0 deletions

View File

@ -394,6 +394,16 @@ class CategoriesController < ApplicationController
Category.preload_user_fields!(guardian, categories)
# Prioritize categories that start with the term, then top-level
# categories, then subcategories
categories =
categories.to_a.sort_by do |category|
[
category.name.downcase.starts_with?(term) ? 0 : 1,
category.parent_category_id.blank? ? 0 : 1,
]
end
if include_ancestors
ancestors = Category.secured(guardian).ancestors_of(categories.map(&:id))

View File

@ -1274,6 +1274,27 @@ RSpec.describe CategoriesController do
end
end
context "with order" do
fab!(:category1) { Fabricate(:category, name: "Category Ordered", parent_category: category) }
fab!(:category2) { Fabricate(:category, name: "Ordered Category", parent_category: category) }
fab!(:category3) { Fabricate(:category, name: "Category Ordered") }
fab!(:category4) { Fabricate(:category, name: "Ordered Category") }
before do
[category1, category2, category3, category4].each do |c|
SearchIndexer.index(c, force: true)
end
end
it "returns in correct order" do
get "/categories/search.json", params: { term: "ordered" }
expect(response.parsed_body["categories"].map { |c| c["id"] }).to eq(
[category4.id, category2.id, category3.id, category1.id],
)
end
end
it "returns user fields" do
sign_in(admin)