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 use 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
我还在acl9 1.2中添加了此功能,因此现在您可以执行以下操作:
company.users :collaborator
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.