Question

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).

Was it helpful?

Solution

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

OTHER TIPS

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

company.users :collaborator
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top