FIX: sort using ruby to avoid N+1 queries (#10915)

FIX: sort using ruby to avoid N+1 queries (#10915)

We are using preload to load tags into topics. When later we try to use order or pluck it is causing N+1

Usually, topics don’t have many tags so sorting using ruby should be reasonably performant.

diff --git a/app/serializers/concerns/topic_tags_mixin.rb b/app/serializers/concerns/topic_tags_mixin.rb
index 990f8ad..e5552af 100644
--- a/app/serializers/concerns/topic_tags_mixin.rb
+++ b/app/serializers/concerns/topic_tags_mixin.rb
@@ -10,10 +10,8 @@ module TopicTagsMixin
   end
 
   def tags
-    # Calling method `pluck` along with `includes` causing N+1 queries
-    order_setting = SiteSetting.tags_sort_alphabetically ? { name: :asc } : { topic_count: :desc }
-    tags = topic.tags.order(order_setting).map(&:name)
-
+    # Calling method `pluck` or `order` along with `includes` causing N+1 queries
+    tags = (SiteSetting.tags_sort_alphabetically ? topic.tags.sort_by(&:name) : topic.tags.sort_by(&:topic_count).reverse).map(&:name)
     if scope.is_staff?
       tags
     else

GitHub sha: d77e31b7

This commit appears in #10915 which was approved by SamSaffron. It was merged by SamSaffron.