简体   繁体   English

Rails 3和Acl9:查找给定对象/角色的所有主题

[英]Rails 3 and Acl9: find all subjects for a given object/role

I'm using rails3 with acl9 for authorization. 我使用Rails3中acl9授权。 I'm trying to grok ARel and the rails way of querying. 我正在尝试使用ARel和Rails的查询方式。

I have a User that belongs to a Company , and the user has a given role (acl9 provides the plumbing) over the Company . 我有属于公司 用户 ,并且用户具有给定角色(acl9提供管道)在本公司 How can I get all Users from a given Company that have a specific role? 如何从给定公司获得具有特定角色的所有用户 I want to filter the results in the DB , not filter them in the application. 我想在数据库中过滤结果 ,而不是在应用程序中过滤结果

I want something like this: 我想要这样的东西:

# 
# authorizable_id = 1 is the company's id
# 'collaborator' and '1' would be params for my scope
#
select * from users
inner join roles_users
on roles_users.user_id = users.id
inner join roles
on roles_users.role_id = roles.id
where roles.authorizable_type='Company'
and   roles.authorizable_id = 1
and   roles.name = 'collaborator';

#usage with scope
@collaborators = User.with_role_and_company('collaborator',current_user.company)

I know rails3 has a sql api, but I come from a Java/Grails place, and most of the ORMs I use have some ORM api (I suppose datamapper works like this, but I'm using plain rails3). 我知道rails3有一个sql api,但是我来自Java / Grails地方,并且我使用的大多数ORM都有一些ORM api(我认为datamapper的工作原理是这样的,但是我使用的是普通的rails3)。

I found out: 我发现:

 class << self
   def with_role_in_company(role, company)
      joins(:roles).
          where(:roles => {:authorizable_type => 'Company'}).
          where(:roles => {:authorizable_id => company.id}).
          where(:roles => {:name => role})
    end
  end

我还在acl9 1.2中添加了此功能,因此现在您可以执行以下操作:

company.users :collaborator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM