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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.