简体   繁体   English

Rails加入多个关联搜索查询

[英]Rails Joins Query on Multiple Association Search

I have two models say User and Roles 我有两个模型,分别是用户和角色

Lets say I have 3 users "A", "B" and "C" and I have 3 roles "X", "Y", "Z" and the relation for users is has_many roles 假设我有3个用户“ A”,“ B”和“ C”,并且我有3个角色“ X”,“ Y”,“ Z”,并且用户的关系为has_many角色

Lets assume A have role X, B have X and Y and C have role X 假设A扮演X角色,B扮演X和Y角色,C扮演X角色

How should I modify my query to get B alone which have both X and Y role 我应该如何修改查询以单独获得具有X和Y角色的B

This is my query which returns users with either X or Y 这是我的查询,返回带有X或Y的用户

User.joins(:roles).where("roles.name IN (?)", ["X", "Y"])

I think work will on after implement below query, I just seeing your code & implemented. 我认为工作将在下面的查询实现后进行,我只是看到您的代码并实现了。

User.joins("LEFT JOIN roles ON roles.name = name").where(["name = 'X', 'Y'"])

Note: Not tested 注意:未经测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM