PERF: Bypass AR and just use raw SQL.

This commit is contained in:
Guo Xiang Tan 2017-09-12 14:34:43 +08:00
parent 475e86d59e
commit 5be5def217
1 changed files with 12 additions and 6 deletions

View File

@ -278,12 +278,18 @@ class TopicView
def post_counts_by_user
@post_counts_by_user ||= begin
return {} if @posts.blank?
Post.where(id: @posts.pluck(:id))
.where("user_id IS NOT NULL")
.group(:user_id)
.order("count_all DESC")
.limit(24)
.count
sql = <<~SQL
SELECT user_id, count(*) AS count_all
FROM posts
WHERE id IN (:post_ids)
AND user_id IS NOT NULL
GROUP BY user_id
ORDER BY count_all DESC
LIMIT 24
SQL
Hash[Post.exec_sql(sql, post_ids: @posts.pluck(:id)).values]
end
end