From d77e31b7e946bcc64f097c81b7eab110187102d6 Mon Sep 17 00:00:00 2001 From: Krzysztof Kotlarek Date: Wed, 14 Oct 2020 18:20:41 +1100 Subject: [PATCH] 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. --- app/serializers/concerns/topic_tags_mixin.rb | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/app/serializers/concerns/topic_tags_mixin.rb b/app/serializers/concerns/topic_tags_mixin.rb index 990f8ad1f30..e5552afe53a 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