We find all roles assigned to the user in the resource, a group in this case.
@user.roles.where(resource: @group)
=> [#<Role:0x00000004a80580
id: 24,
name: "organizer",
resource_type: "Group",
resource_id: 11,
created_at: Wed, 21 Mar 2018 17:15:57 UTC +00:00,
updated_at: Wed, 21 Mar 2018 17:15:57 UTC +00:00>]
We map the roles converting the name
attribute to a symbol.
@user.roles.where(resource: @group).map do |role|
role.name.to_sym
end
=> [:organizer]
Now we only need to iterate and remove.
def remove_all_user_roles_for_group
user_roles.each do |role|
@user.remove_role role, @group
end
end
def user_roles
@user.roles.where(resource: @group).map do |role|
role.name.to_sym
end
end
I'd suggest you change the
user_roles
to take advantage of pluck (to fetch only name fromroles
table). Here's how I use thisThen you can do
user.roles_for(project)
oruser.role_names_for(project)
which usespluck
to only fetch name.