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

Optimize finding a membership for a user to avoid extra queries

parent bb61d0161098
......@@ -1073,6 +1073,15 @@ def lock_access!
super
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
# override, from Devise::Validatable
......
......@@ -40,9 +40,7 @@ def relative_path
end
def permission
return unless request&.current_user
request.current_user.members.find_by(source: object)&.human_access
membership&.human_access
end
# Project only attributes
......@@ -55,11 +53,11 @@ def permission
unless: lambda { |_instance, _options| project? }
def leave_path
leave_group_group_members_path(object)
leave_group_members_path(object)
end
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)
else
false
......@@ -73,4 +71,12 @@ def number_projects_with_delimiter
def number_users_with_delimiter
number_with_delimiter(object.member_count)
end
private
def membership
return unless request.current_user
@membership ||= request.current_user.membership_for_object(object)
end
end
......@@ -34,7 +34,7 @@
end
describe 'for a project' do
set(:object) do
let(:object) do
create(:project, :with_avatar,
description: 'Awesomeness')
end
......@@ -55,7 +55,7 @@
end
describe 'for a group', :nested_groups do
set(:object) do
let(:object) do
create(:group, :nested, :with_avatar,
description: 'Awesomeness')
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