Rails way for querying join table in has_and_belongs_to_many
Posted
by Michelle
on Stack Overflow
See other posts from Stack Overflow
or by Michelle
Published on 2010-03-22T17:56:14Z
Indexed on
2010/03/22
18:11 UTC
Read the original article
Hit count: 271
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
© Stack Overflow or respective owner