PERF: Remove N+1 queries on basic category serializer.

PERF: Remove N+1 queries on basic category serializer.

diff --git a/plugin.rb b/plugin.rb
index 24bb46c..2807697 100644
--- a/plugin.rb
+++ b/plugin.rb
@@ -333,7 +333,7 @@ SQL
     end
 
     def include_custom_fields?
-      SiteSetting.show_filter_by_solved_status && custom_fields.present?
+      object.custom_field_preloaded?("enable_accepted_answers") && SiteSetting.show_filter_by_solved_status && custom_fields.present?
     end
   end
 
diff --git a/spec/serializers/basic_category_serializer_spec.rb b/spec/serializers/basic_category_serializer_spec.rb
new file mode 100644
index 0000000..c707a9a
--- /dev/null
+++ b/spec/serializers/basic_category_serializer_spec.rb
@@ -0,0 +1,21 @@
+require 'rails_helper'
+
+describe BasicCategorySerializer do
+  let(:category) { Fabricate(:category) }
+  let(:guardian) { Guardian.new }
+
+  before do
+    SiteSetting.show_filter_by_solved_status = true
+    category.custom_fields["enable_accepted_answers"] = true
+    category.save_custom_fields
+  end
+
+  it "should include custom fields only if its preloaded" do
+    json = described_class.new(category, scope: guardian, root: false).as_json
+    expect(json.to_s).not_to include("custom_fields")
+
+    category.expects(:custom_field_preloaded?).returns(true)
+    json = described_class.new(category, scope: guardian, root: false).as_json
+    expect(json.to_s).to include("custom_fields")
+  end  
+end

GitHub sha: 8beaa6c1

Can we test this without the mock?

1 Like

It’s no longer needed as per the commit