/moderator/dashboard: optimize sql queries
* Converts queries to use active record instead of raw sql. This ensures that user objects are loaded by rails in the join, so that we don't have to issue `User.find` calls to load users one-by-one. * Use `.includes` to preload associations used in the view, to avoid additional N+1 query problems (primarily, calls to link_to_user also causing users to be loaded one-by-one).
This commit is contained in:
@@ -2,28 +2,13 @@ module Moderator
|
||||
module Dashboard
|
||||
module Queries
|
||||
class PostAppeal
|
||||
attr_reader :post, :count
|
||||
|
||||
def self.all(min_date)
|
||||
sql = <<-EOS
|
||||
SELECT post_appeals.post_id, count(*)
|
||||
FROM post_appeals
|
||||
JOIN posts ON posts.id = post_appeals.post_id
|
||||
WHERE
|
||||
post_appeals.created_at > ?
|
||||
and posts.is_deleted = true
|
||||
and posts.is_pending = false
|
||||
GROUP BY post_appeals.post_id
|
||||
ORDER BY count(*) DESC
|
||||
LIMIT 10
|
||||
EOS
|
||||
|
||||
ActiveRecord::Base.select_all_sql(sql, min_date).map {|x| new(x)}
|
||||
end
|
||||
|
||||
def initialize(hash)
|
||||
@post = ::Post.find(hash["post_id"])
|
||||
@count = hash["count"]
|
||||
::Post.joins(:appeals).includes(:uploader, :flags, appeals: [:creator])
|
||||
.deleted
|
||||
.where("post_appeals.created_at > ?", min_date)
|
||||
.group(:id)
|
||||
.order("count(*) desc")
|
||||
.limit(10)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user