Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rolify: Remove all roles for user

Rolify: Remove All Roles For User In a Specific Resource

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
@lenart

This comment has been minimized.

Copy link

@lenart lenart commented Nov 29, 2020

I'd suggest you change the user_roles to take advantage of pluck (to fetch only name from roles table). Here's how I use this

module RoleHelers
  def roles_for(resource)
    roles.where(resource: resource)
  end

  def role_names_for(resource)
    roles_for(resource).pluck(:name)
  end
end

class User
  include RolesHelper
end

Then you can do user.roles_for(project) or user.role_names_for(project) which uses pluck to only fetch name.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment