From 34ec90bd738283ee894c3059039e7868a4049a17 Mon Sep 17 00:00:00 2001 From: Thorsten Eckel Date: Wed, 18 Oct 2017 11:16:49 +0200 Subject: [PATCH] Refactoring: Removed N+1 performance issue by implementing correct join. Thanks to @rolfschmidt! --- app/models/concerns/has_groups.rb | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/app/models/concerns/has_groups.rb b/app/models/concerns/has_groups.rb index 8191049d5..4d420059a 100644 --- a/app/models/concerns/has_groups.rb +++ b/app/models/concerns/has_groups.rb @@ -300,11 +300,15 @@ module HasGroups access = ensure_group_access_list_parameter(access) # check direct access - ids = group_through.klass.includes(name.downcase).where(group_id: group_id, access: access, table_name => { active: true }).pluck(group_through.foreign_key) - ids ||= [] + instances = joins(group_through.name) + .where( group_through.table_name => { group_id: group_id, access: access }, active: true ) - # get instances and check for required permission - instances = where(id: ids).select(&:groups_access_permission?) + if respond_to?(:permissions?) + permissions = Permission.with_parents('ticket.agent') + instances = instances + .joins(roles: :permissions) + .where(roles: { active: true }, permissions: { name: permissions, active: true }) + end # check indirect access through roles if possible return instances if !respond_to?(:role_access)