Commit e013d398 authored by Bob Van Landuyt's avatar Bob Van Landuyt

Optimize finding a membership for a user to avoid extra queries

parent 951abe2b
...@@ -1073,6 +1073,15 @@ class User < ActiveRecord::Base ...@@ -1073,6 +1073,15 @@ class User < ActiveRecord::Base
super super
end end
# Get the membership for an object without loading the source of the membership
#
# This loads the entire `members` relation of the user, used on `current_user`
def membership_for_object(object)
members.sort('access_level_asc').detect do |member|
object.is_a?(member.source_type.constantize) && member.source_id == object.id
end
end
protected protected
# override, from Devise::Validatable # override, from Devise::Validatable
......
...@@ -40,9 +40,7 @@ class GroupChildEntity < Grape::Entity ...@@ -40,9 +40,7 @@ class GroupChildEntity < Grape::Entity
end end
def permission def permission
return unless request&.current_user membership&.human_access
request.current_user.members.find_by(source: object)&.human_access
end end
# Project only attributes # Project only attributes
...@@ -55,11 +53,11 @@ class GroupChildEntity < Grape::Entity ...@@ -55,11 +53,11 @@ class GroupChildEntity < Grape::Entity
unless: lambda { |_instance, _options| project? } unless: lambda { |_instance, _options| project? }
def leave_path def leave_path
leave_group_group_members_path(object) leave_group_members_path(object)
end end
def can_leave def can_leave
if membership = object.members_and_requesters.find_by(user: request.current_user) if membership
can?(request.current_user, :destroy_group_member, membership) can?(request.current_user, :destroy_group_member, membership)
else else
false false
...@@ -73,4 +71,12 @@ class GroupChildEntity < Grape::Entity ...@@ -73,4 +71,12 @@ class GroupChildEntity < Grape::Entity
def number_users_with_delimiter def number_users_with_delimiter
number_with_delimiter(object.member_count) number_with_delimiter(object.member_count)
end end
private
def membership
return unless request.current_user
@membership ||= request.current_user.membership_for_object(object)
end
end end
...@@ -34,7 +34,7 @@ describe GroupChildEntity do ...@@ -34,7 +34,7 @@ describe GroupChildEntity do
end end
describe 'for a project' do describe 'for a project' do
set(:object) do let(:object) do
create(:project, :with_avatar, create(:project, :with_avatar,
description: 'Awesomeness') description: 'Awesomeness')
end end
...@@ -55,7 +55,7 @@ describe GroupChildEntity do ...@@ -55,7 +55,7 @@ describe GroupChildEntity do
end end
describe 'for a group', :nested_groups do describe 'for a group', :nested_groups do
set(:object) do let(:object) do
create(:group, :nested, :with_avatar, create(:group, :nested, :with_avatar,
description: 'Awesomeness') description: 'Awesomeness')
end end
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment