我有一个用户模型和一个带有has_and_belongs_to_many reliationship的角色模型.连接表是roles_users(两列 - 用户的PK和角色),没有相应的模型.
我想有一个方法返回具有给定角色的所有用户.在SQL中,它就像是
SELECT u.id FROM role.r, roles_users ru WHERE r.role_id = #{role.id} AND r.role_id = ru.role_id
Run Code Online (Sandbox Code Playgroud)
我看到Rails的activerecord有一个find_by_sql方法,但它只期望返回一个结果.
什么是"Rails方式"给我一个具有给定角色的用户列表,例如
def self.find_users_with_role(role)
users = []
users << # Some ActiveRecord magic or custom code here..?
end
Run Code Online (Sandbox Code Playgroud)