A platform for community discussion. Free, open, simple.
PERF: Fix N+1 when loading categories with custom fields (#26241)
Bianca Nenciu42354ca1adf4
diff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rbindex 4be599d3c56..3d6da8e307a 100644--- a/app/controllers/categories_controller.rb+++ b/app/controllers/categories_controller.rb@@ -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-leveldiff --git a/spec/requests/categories_controller_spec.rb b/spec/requests/categories_controller_spec.rbindex 51496f8fcfc..076045fea7f 100644--- a/spec/requests/categories_controller_spec.rb+++ b/spec/requests/categories_controller_spec.rb@@ -1153,12 +1153,19 @@ RSpec.describe CategoriesController doendit "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: "Notfoo" } }- queries = track_sql_queries { get "/categories/search.json", params: { term: "Foo" } }+ expect(queries.length).to eq(5)- expect(queries.length).to eq(4)+ expect(response.parsed_body["categories"].length).to eq(1)+ expect(response.parsed_body["categories"][0]["custom_fields"]).to eq("bob" => "marley")endcontext "without include_ancestors" do