comments: minimize sql queries.

Certain parts of comment rendering triggered sql queries that we didn't
really need to do. Rework things to avoid this.

* Preload comment creators in order to display commenter names with link_to_user.

* Preload comment votes in order to display "undo vote" links. Only preload
  votes for members since anonymous users can't vote and don't have "undo
  vote" links.

* Rework various conditionals to do the filtering in Ruby so that we
  avoid issuing any extra queries in sql.

* Avoid issuing any queries at all when the post doesn't have any
  comments (when last_commented_at is blank).
This commit is contained in:
evazion
2019-08-20 20:53:40 -05:00
parent 2cf929ad6e
commit b283281e5e
9 changed files with 30 additions and 60 deletions

View File

@@ -22,26 +22,6 @@ class Comment < ApplicationRecord
)
module SearchMethods
def recent
reorder("comments.id desc").limit(6)
end
def hidden(user)
if user.is_moderator?
where("(score < ? and is_sticky = false) or is_deleted = true", user.comment_threshold)
else
where("score < ? and is_sticky = false", user.comment_threshold)
end
end
def visible(user)
if user.is_moderator?
where("(score >= ? or is_sticky = true) and is_deleted = false", user.comment_threshold)
else
where("score >= ? or is_sticky = true", user.comment_threshold)
end
end
def deleted
where("comments.is_deleted = true")
end
@@ -172,9 +152,16 @@ class Comment < ApplicationRecord
end
def voted_by?(user)
return false if user.is_anonymous?
user.id.in?(votes.map(&:user_id))
end
def visible_by?(user, show_thresholded: false, show_deleted: false)
return false if is_deleted? && !show_deleted && !user.is_moderator?
return false if score < user.comment_threshold && !is_sticky? && !show_thresholded
true
end
def hidden_attributes
super + [:body_index]
end

View File

@@ -51,7 +51,7 @@ class Post < ApplicationRecord
has_many :appeals, :class_name => "PostAppeal", :dependent => :destroy
has_many :votes, :class_name => "PostVote", :dependent => :destroy
has_many :notes, :dependent => :destroy
has_many :comments, -> {includes(:creator, :updater).order("comments.id")}, :dependent => :destroy
has_many :comments, -> {order("comments.id")}, :dependent => :destroy
has_many :children, -> {order("posts.id")}, :class_name => "Post", :foreign_key => "parent_id"
has_many :approvals, :class_name => "PostApproval", :dependent => :destroy
has_many :disapprovals, :class_name => "PostDisapproval", :dependent => :destroy