Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rolify and getting a list of User with specific access to a resource

I have two models Organization and Users which I'm using Rolify to connect.

Users have roles and Organization is a resource.

This works great however my problem is trying to get a list of users for a particular resource. I would like to get a list of all users which have any role on that resource (and I don't care about Class level roles like universal admins etc.)

I tried doing something like below, but it's terrible and it also still returns a list of class level admins (those with admin but not actually on any particular resource).

class Organization < ActiveRecord::Base
  resourcify

  def users
    # this is terrible and still doesn't work right.
    User.with_role(:admin, self) + User.with_role(:press, self)
  end
end

class User < ActiveRecord::Base
  rolify

  def organizations
    Organization.with_roles(Role.role_names, self).uniq
  end
end

Any ideas?

like image 391
ere Avatar asked Jan 08 '23 00:01

ere


1 Answers

Try this.

has_many :users, through: :roles, class_name: 'User', source: :users

This should only add those that are using the roles model (skipping those on the class). You could also try something more explicit with conditions see this issue/PR:

https://github.com/RolifyCommunity/rolify/pull/181

like image 137
holden Avatar answered Jan 21 '23 16:01

holden