PERF: Remove n+1 in user directory (#13501)

PERF: Remove n+1 in user directory (#13501)

diff --git a/app/controllers/directory_items_controller.rb b/app/controllers/directory_items_controller.rb
index abfe46e..ab82011 100644
--- a/app/controllers/directory_items_controller.rb
+++ b/app/controllers/directory_items_controller.rb
@@ -9,7 +9,7 @@ class DirectoryItemsController < ApplicationController
     period = params.require(:period)
     period_type = DirectoryItem.period_types[period.to_sym]
     raise Discourse::InvalidAccess.new(:period_type) unless period_type
-    result = DirectoryItem.where(period_type: period_type).includes(:user)
+    result = DirectoryItem.where(period_type: period_type).includes(user: :user_custom_fields)
 
     if params[:group]
       group = Group.find_by(name: params[:group])
@@ -96,7 +96,12 @@ class DirectoryItemsController < ApplicationController
 
     serializer_opts = {}
     if params[:user_field_ids]
-      serializer_opts[:user_field_ids] = params[:user_field_ids]&.split("|")&.map(&:to_i)
+      serializer_opts[:user_custom_field_map] = {}
+
+      user_field_ids = params[:user_field_ids]&.split("|")&.map(&:to_i)
+      user_field_ids.each do |user_field_id|
+        serializer_opts[:user_custom_field_map]["#{User::USER_FIELD_PREFIX}#{user_field_id}"] = user_field_id
+      end
     end
 
     if params[:plugin_column_ids]
diff --git a/app/serializers/directory_item_serializer.rb b/app/serializers/directory_item_serializer.rb
index 1e18f84..aa833e1 100644
--- a/app/serializers/directory_item_serializer.rb
+++ b/app/serializers/directory_item_serializer.rb
@@ -8,11 +8,20 @@ class DirectoryItemSerializer < ApplicationSerializer
     attributes :user_fields
 
     def user_fields
-      object.user_fields(@options[:user_field_ids])
+      fields = {}
+
+      object.user_custom_fields.each do |cuf|
+        user_field_id = @options[:user_custom_field_map][cuf.name]
+        if user_field_id
+          fields[user_field_id] = cuf.value
+        end
+      end
+
+      fields
     end
 
     def include_user_fields?
-      user_fields.present?
+      @options[:user_custom_field_map].present?
     end
   end
 

GitHub sha: 6e1fa7b08258d1a4d8fa9492e9b1e782e240c47a

This commit appears in #13501 which was approved by Falco. It was merged by markvanlan.