如何根据多对多相关模型的属性查找记录?

楷模…

InternalUser has_many :internal_user_roles has_many :roles, :through => :internal_user_roles InternalUserRole belongs_to :internal_user belongs_to :role Role has_many :internal_user_roles has_many :internal_users, :through => :internal_user_roles 

使用新的ActiveRecord查询API,我如何找到具有“ADMIN”角色的所有InternalUser

换句话说,我该如何生成此查询…

 SELECT * FROM internal_users i, internal_user_roles ir, roles r WHERE i.id = ir.internal_user_id AND r.id = ir.internal_user_id AND r.name = 'ADMIN' 

理想情况下,您应该从作为admin角色的对象开始:

 role = Role.find_by_name('ADMIN') 

然后,您只需查询该角色的内部用户:

 role.internal_users 

如果您想更进一步,您应该注意,可以进一步查询ActiveRecord中的所有关联:

 role.internal_users.where(:first_name => 'Bill').limit(5) 

回到原始问题,您也可以查询InternalUser模型:

 InternalUser.includes(:roles).where(['roles.id = ?', role]) 

或者更快,但代码更复杂:

 InternalUser.includes(:internal_user_roles).where(['internal_user_roles.role_id = ?', role]) 

要直接翻译SQL查询,您还可以执行以下操作:

 InternalUser.includes(:roles).where("roles.name = 'ADMIN'") 

您还可以通过在末尾添加“to_sql”调用来查看ActiveRecord将生成的SQL(对于任何这些查询),如下所示:

 InternalUser.includes(:roles).where("roles.name = 'ADMIN'").to_sql