From 843023d7c97551c304eebe84fa6ed09c833bd789 Mon Sep 17 00:00:00 2001 From: Vikhyat Korrapati Date: Thu, 17 Apr 2014 21:57:42 +0530 Subject: [PATCH] Fix user_badges n+1 query. --- app/controllers/user_badges_controller.rb | 3 ++- app/models/user.rb | 2 +- app/serializers/user_badge_serializer.rb | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/app/controllers/user_badges_controller.rb b/app/controllers/user_badges_controller.rb index 3dd527388d7..7d695063081 100644 --- a/app/controllers/user_badges_controller.rb +++ b/app/controllers/user_badges_controller.rb @@ -6,8 +6,9 @@ class UserBadgesController < ApplicationController user_badges = user.user_badges else badge = fetch_badge_from_params - user_badges = badge.user_badges.order('granted_at DESC').limit(200).to_a + user_badges = badge.user_badges.order('granted_at DESC').limit(200) end + user_badges = user_badges.includes(:user, :granted_by, badge: :badge_type) render_serialized(user_badges, UserBadgeSerializer, root: "user_badges") end diff --git a/app/models/user.rb b/app/models/user.rb index 238a2a0f6c1..80d3c3bdf55 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -497,7 +497,7 @@ class User < ActiveRecord::Base end def featured_user_badges - user_badges.joins(:badge).order('badges.badge_type_id ASC, badges.grant_count ASC').includes(:granted_by, badge: :badge_type).limit(3) + user_badges.joins(:badge).order('badges.badge_type_id ASC, badges.grant_count ASC').includes(:user, :granted_by, badge: :badge_type).limit(3) end def self.count_by_signup_date(sinceDaysAgo=30) diff --git a/app/serializers/user_badge_serializer.rb b/app/serializers/user_badge_serializer.rb index eda18b11ea9..f751ecd6dd7 100644 --- a/app/serializers/user_badge_serializer.rb +++ b/app/serializers/user_badge_serializer.rb @@ -1,7 +1,7 @@ class UserBadgeSerializer < ApplicationSerializer attributes :id, :granted_at - has_one :user has_one :badge + has_one :user, serializer: BasicUserSerializer, root: :users has_one :granted_by, serializer: BasicUserSerializer, root: :users end