PERF: Fix N+1 when loading categories with custom fields (#26241)

Follow up to commit a90b88af56.
This commit is contained in:
Bianca Nenciu 2024-03-19 14:11:19 +02:00 committed by GitHub
parent 98eb014bdb
commit 42354ca1ad
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 14 additions and 3 deletions

View File

@ -410,6 +410,10 @@ class CategoriesController < ApplicationController
.select("categories.*, t.slug topic_slug")
.limit(limit || MAX_CATEGORIES_LIMIT)
if Site.preloaded_category_custom_fields.present?
Category.preload_custom_fields(categories, Site.preloaded_category_custom_fields)
end
Category.preload_user_fields!(guardian, categories)
# Prioritize categories that start with the term, then top-level

View File

@ -1153,12 +1153,19 @@ RSpec.describe CategoriesController do
end
it "does not generate N+1 queries" do
# Set up custom fields
Site.preloaded_category_custom_fields << "bob"
category2.upsert_custom_fields("bob" => "marley")
# Warm up caches
get "/categories/search.json", params: { term: "Foo" }
get "/categories/search.json", params: { term: "Notfoo" }
queries = track_sql_queries { get "/categories/search.json", params: { term: "Foo" } }
queries = track_sql_queries { get "/categories/search.json", params: { term: "Notfoo" } }
expect(queries.length).to eq(4)
expect(queries.length).to eq(5)
expect(response.parsed_body["categories"].length).to eq(1)
expect(response.parsed_body["categories"][0]["custom_fields"]).to eq("bob" => "marley")
end
context "without include_ancestors" do