PERF: Fix N+1 when searching categories (#26223)

This commit is contained in:
Bianca Nenciu 2024-03-18 19:01:17 +02:00 committed by GitHub
parent 8ae462c724
commit a90b88af56
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 21 additions and 1 deletions

View File

@ -394,7 +394,21 @@ class CategoriesController < ApplicationController
categories_count = categories.count
categories = categories.limit(limit || MAX_CATEGORIES_LIMIT)
categories =
categories
.includes(
:uploaded_logo,
:uploaded_logo_dark,
:uploaded_background,
:uploaded_background_dark,
:tags,
:tag_groups,
:form_templates,
category_required_tag_groups: :tag_group,
)
.joins("LEFT JOIN topics t on t.id = categories.topic_id")
.select("categories.*, t.slug topic_slug")
.limit(limit || MAX_CATEGORIES_LIMIT)
Category.preload_user_fields!(guardian, categories)

View File

@ -1152,6 +1152,12 @@ RSpec.describe CategoriesController do
[category, category2, subcategory].each { |c| SearchIndexer.index(c, force: true) }
end
it "does not generate N+1s" do
queries = track_sql_queries { get "/categories/search.json", params: { term: "Foo" } }
expect(queries.length).to eq(6)
end
context "without include_ancestors" do
it "doesn't return ancestors" do
get "/categories/search.json", params: { term: "Notfoo" }