From 5d5dbaca95d1fa944a687e07709c530ed7cfbd62 Mon Sep 17 00:00:00 2001 From: Jamie Gaskins Date: Tue, 5 Oct 2021 04:05:01 -0400 Subject: [PATCH] Eager-load comment user data (#14902) * Eager-load comment user data Profiles and user settings are loaded for on each comment author. On posts with many comments, this invokes a *lot* of DB queries. This commit replaces 2 queries per comment with 2 queries for all comments. * Fix where I misunderstood limit's purpose This implementation is too clever. It looks like it should just be getting all but the last, but it uses the fact that the default is 0 to default to getting all of them. This isn't readily understandable to someone reading the code. I don't have a suggestion to fix it yet so I'm just going to leave it as-is for now. --- app/models/comment.rb | 6 +++++- app/views/comments/index.html.erb | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/app/models/comment.rb b/app/models/comment.rb index 213eb3cda..e0f2beb2a 100644 --- a/app/models/comment.rb +++ b/app/models/comment.rb @@ -91,7 +91,11 @@ class Comment < ApplicationRecord alias touch_by_reaction save def self.tree_for(commentable, limit = 0) - commentable.comments.includes(:user).arrange(order: "score DESC").to_a[0..limit - 1].to_h + commentable.comments + .includes(user: %i[setting profile]) + .arrange(order: "score DESC") + .to_a[0..limit - 1] + .to_h end def search_id diff --git a/app/views/comments/index.html.erb b/app/views/comments/index.html.erb index 5805bdc7d..848ef034c 100644 --- a/app/views/comments/index.html.erb +++ b/app/views/comments/index.html.erb @@ -124,7 +124,7 @@
<% if @root_comment.present? %> <% cache ["comment_root-view-root_#{user_signed_in?}", @root_comment] do %> - <%= tree_for(@root_comment, @root_comment.subtree.includes(:user).arrange[@root_comment], @commentable) %> + <%= tree_for(@root_comment, @root_comment.subtree.includes(user: %i[setting profile]).arrange[@root_comment], @commentable) %> <% end %> <% else %> <% Comment.tree_for(@commentable).each do |comment, sub_comments| %>