/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:
@@ -1,28 +1,16 @@
|
||||
module Moderator
|
||||
module Dashboard
|
||||
module Queries
|
||||
class Upload
|
||||
attr_reader :user, :count
|
||||
|
||||
class Upload < ::Struct.new(:user, :count)
|
||||
def self.all(min_date, max_level)
|
||||
sql = <<-EOS
|
||||
select uploader_id, count(*)
|
||||
from posts
|
||||
join users on uploader_id = users.id
|
||||
where
|
||||
posts.created_at > ?
|
||||
and level <= ?
|
||||
group by posts.uploader_id
|
||||
order by count(*) desc
|
||||
limit 10
|
||||
EOS
|
||||
|
||||
ActiveRecord::Base.select_all_sql(sql, min_date, max_level).map {|x| new(x)}
|
||||
end
|
||||
|
||||
def initialize(hash)
|
||||
@user = ::User.find(hash["uploader_id"])
|
||||
@count = hash["count"]
|
||||
::Post.joins(:uploader)
|
||||
.where("posts.created_at > ?", min_date)
|
||||
.where("users.level <= ?", max_level)
|
||||
.group(:uploader)
|
||||
.order("count(*) desc")
|
||||
.limit(10)
|
||||
.count
|
||||
.map { |user, count| new(user, count) }
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user