开发者

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

I'm using rails3 with acl9 for authorization. I'm trying to grok ARel and the rails way of querying.

I have a User that belongs to a Company, and the user has a given role (acl9 provides the plumbing) over the Company. 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 us开发者_如何学Pythone have some ORM api (I suppose datamapper works like this, but I'm using plain 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


I also added this feature in acl9 1.2, so now you can just do:

company.users :collaborator
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜