Merge pull request #1325 from ZogStriP/fix-n-plus-one-query-for-avatars

FIX: N+1 query for avatars
This commit is contained in:
Robin Ward 2013-08-14 06:57:31 -07:00
commit 890d3d0f45
6 changed files with 15 additions and 16 deletions

View file

@ -313,7 +313,7 @@ class UsersController < ApplicationController
results = UserSearch.search term, topic_id
render json: { users: results.as_json(only: [ :username, :name ],
render json: { users: results.as_json(only: [ :username, :name, :use_uploaded_avatar, :upload_avatar_template, :uploaded_avatar_id],
methods: :avatar_template) }
end

View file

@ -301,15 +301,7 @@ class User < ActiveRecord::Base
user = User.select([:email, :use_uploaded_avatar, :uploaded_avatar_template, :uploaded_avatar_id])
.where(email: email.downcase)
.first
if user.present?
if SiteSetting.allow_uploaded_avatars? && user.use_uploaded_avatar
# the avatars might take a while to generate
# so return the url of the original image in the meantime
user.uploaded_avatar_template.present? ? user.uploaded_avatar_template : user.uploaded_avatar.url
else
User.gravatar_template(email)
end
end
user.avatar_template if user.present?
end
def self.gravatar_template(email)
@ -323,11 +315,17 @@ class User < ActiveRecord::Base
# - emails
def small_avatar_url
template = User.avatar_template(email)
template.gsub(/\{size\}/, "60")
template.gsub("{size}", "60")
end
def avatar_template
User.avatar_template(email)
if SiteSetting.allow_uploaded_avatars? && use_uploaded_avatar
# the avatars might take a while to generate
# so return the url of the original image in the meantime
uploaded_avatar_template.present? ? uploaded_avatar_template : uploaded_avatar.url
else
User.gravatar_template(email)
end
end
# Updates the denormalized view counts for all users

View file

@ -1,7 +1,7 @@
class UserSearch
def self.search term, topic_id = nil
sql = User.sql_builder(
"select id, username, name, email from users u
"select id, username, name, email, use_uploaded_avatar, uploaded_avatar_template, uploaded_avatar_id from users u
/*left_join*/
/*where*/
/*order_by*/")

View file

@ -12,7 +12,9 @@ class AvatarLookup
private
def users
@users ||= User.where(:id => @user_ids).select([:id, :email, :username]).inject({}) do |hash, user|
@users ||= User.where(:id => @user_ids)
.select([:id, :email, :username, :use_uploaded_avatar, :uploaded_avatar_template, :uploaded_avatar_id])
.inject({}) do |hash, user|
hash.merge({user.id => user})
end
end

View file

@ -85,7 +85,7 @@ class LocalStore
end
def get_path_for_avatar(file, upload, size)
relative_avatar_template(upload).gsub(/\{size\}/, size.to_s)
relative_avatar_template(upload).gsub("{size}", size.to_s)
end
def relative_avatar_template(upload)

View file

@ -130,7 +130,6 @@ class TopicQuery
end
def list_topics_by(user)
Rails.logger.info ">>> #{user.id}"
create_list(:user_topics) do |topics|
topics.where(user_id: user.id)
end