From c5f9b2be826c05e5f06d424f5c110976ad0b68c4 Mon Sep 17 00:00:00 2001 From: Sean McGivern Date: Fri, 22 Mar 2019 15:51:14 +0000 Subject: Remove N+1 queries from users autocomplete Both of these were related to groups: 1. We need to preload routes (using the `with_route` scope) if we're going to get the group's path. 2. We were counting each group's members separately. They're in the same commit because the spec for N+1 detection wouldn't pass with only one of these fixes. --- .../concerns/users/participable_service.rb | 26 +++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) (limited to 'app/services') diff --git a/app/services/concerns/users/participable_service.rb b/app/services/concerns/users/participable_service.rb index 6713b6617ae..a3cc6014fd3 100644 --- a/app/services/concerns/users/participable_service.rb +++ b/app/services/concerns/users/participable_service.rb @@ -28,19 +28,35 @@ module Users end def groups - current_user.authorized_groups.sort_by(&:path).map do |group| - group_as_hash(group) + group_counts = GroupMember + .in_groups(current_user.authorized_groups) + .non_request + .count_users_by_group_id + + current_user.authorized_groups.with_route.sort_by(&:path).map do |group| + group_as_hash(group, group_counts) end end private def user_as_hash(user) - { type: user.class.name, username: user.username, name: user.name, avatar_url: user.avatar_url } + { + type: user.class.name, + username: user.username, + name: user.name, + avatar_url: user.avatar_url + } end - def group_as_hash(group) - { type: group.class.name, username: group.full_path, name: group.full_name, avatar_url: group.avatar_url, count: group.users.count } + def group_as_hash(group, group_counts) + { + type: group.class.name, + username: group.full_path, + name: group.full_name, + avatar_url: group.avatar_url, + count: group_counts.fetch(group.id, 0) + } end end end -- cgit v1.2.3