PERF: Fix N+1 queries on private messages route.

PERF: Fix N+1 queries on private messages route.

diff --git a/app/serializers/topic_list_item_serializer.rb b/app/serializers/topic_list_item_serializer.rb
index d0cff44..a0addd8 100644
--- a/app/serializers/topic_list_item_serializer.rb
+++ b/app/serializers/topic_list_item_serializer.rb
@@ -88,7 +88,8 @@ class TopicListItemSerializer < ListableTopicSerializer
   end
 
   def allowed_user_count
-    object.allowed_users.count
+    # Don't use count as it will result in a query
+    object.allowed_users.length
   end
 
   def include_allowed_user_count?
diff --git a/lib/topic_query.rb b/lib/topic_query.rb
index e94b03a..73aa372 100644
--- a/lib/topic_query.rb
+++ b/lib/topic_query.rb
@@ -528,23 +528,19 @@ class TopicQuery
     options = @options
     options.reverse_merge!(per_page: per_page_setting)
 
-    result = Topic.includes(:tags)
+    result = Topic.includes(:tags, :allowed_users)
 
     if type == :group
-      result = result
-        .includes(:allowed_users)
-        .joins("INNER JOIN topic_allowed_groups tag ON tag.topic_id = topics.id AND tag.group_id IN (SELECT id FROM groups WHERE LOWER(name) = '#{PG::Connection.escape_string(@options[:group_name].downcase)}')")
+      result = result.joins(
+        "INNER JOIN topic_allowed_groups tag ON tag.topic_id = topics.id AND tag.group_id IN (SELECT id FROM groups WHERE LOWER(name) = '#{PG::Connection.escape_string(@options[:group_name].downcase)}')"
+      )
 
       unless user.admin?
         result = result.joins("INNER JOIN group_users gu ON gu.group_id = tag.group_id AND gu.user_id = #{user.id.to_i}")
       end
-
-      result
     elsif type == :user
-      result = result.includes(:allowed_users)
       result = result.where("topics.id IN (SELECT topic_id FROM topic_allowed_users WHERE user_id = #{user.id.to_i})")
     elsif type == :all
-      result = result.includes(:allowed_users)
       result = result.where("topics.id IN (
             SELECT topic_id
             FROM topic_allowed_users

GitHub sha: dbc630f4