【问题标题】:Rolify and getting a list of User with specific access to a resourceRolify 并获取对资源具有特定访问权限的用户列表
【发布时间】:2015-12-14 12:50:39
【问题描述】:

我有两个模型 OrganizationUsers 我正在使用 Rolify 进行连接。

用户有角色,组织是一种资源。

这很好用,但是我的问题是尝试获取特定资源的用户列表。我想获取在该资源上具有任何角色的所有用户的列表(而且我不关心通用管理员等类级别的角色)

我尝试做类似下面的事情,但它很糟糕,它仍然返回一个类级别管理员的列表(那些有管理员但实际上不在任何特定资源上的人)。

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

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 cancan cancancan rolify


    【解决方案1】:

    试试这个。

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

    这应该只添加使用角色模型的那些(跳过类中的那些)。您还可以尝试更明确的条件,请参阅此问题/PR:

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

    【讨论】:

    • 这可行,但是如果调用Organization.first.users,它将为多个分配的角色返回双重条目。 Organization.first.users.uniq 可以工作,但Organization.first.users.with_role :press 不会。我真的希望 rolify 能够按照问题中描述的方式工作。获取特定用户有点棘手。
    【解决方案2】:

    添加此答案以便对其他人有所帮助。

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

    这是通过内部加入角色表来过滤用户,该表具有与特定组织对象相关的角色条目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多