4

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?

ere
  • 1,739
  • 3
  • 19
  • 41

2 Answers2

9

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

holden
  • 13,471
  • 22
  • 98
  • 160
  • 1
    this works, however if `Organization.first.users` is called, it will return double entries for multiple assigned roles. `Organization.first.users.uniq` will work, however `Organization.first.users.with_role :press` will not. I really wished rolify would work the way it's described in the question. Getting specific users is a bit tricky. – Adam Cooper Feb 06 '17 at 15:43
1

Adding this answer so that this may help for others.

class Organization < ActiveRecord::Base
  resourcify

  def users
    User.joins(:roles).where(
      roles: { resource_type: 'Organization', resource_id: self.id }
    )
  end
end

This is to filter out the users by inner joining roles table which has role entries related to a particular Organization object.

Ashik Salman
  • 1,819
  • 11
  • 15