Rails way for querying join table in has_and_belongs_to_many
- by Michelle
I have a user model and a role model with a has_and_belongs_to_many reliationship. The join table is roles_users (two columns - the PK of the user and the role) and has no corresponding model.
I want to have a method that returns all users with a given role. In SQL that'd be something like
SELECT u.id FROM role.r, roles_users ru WHERE r.role_id = #{role.id} AND r.role_id = ru.role_id
I see that Rails' activerecord has a find_by_sql method, but it's only expecting one results to be returned.
What is the "Rails Way" to give me a list of users with a given role e.g.
def self.find_users_with_role(role)
users = []
users << # Some ActiveRecord magic or custom code here..?
end