Reputation: 3
In my code, a Room has_many :users, and Users have a :name attribute
Let's also say I have NameArr, an array of names.
What's the best way to get all Rooms that have all the users in Arr?
(e.g. if Arr = ["John", "Mark", "Matt"] then I want all Rooms having a User with name "John" AND a User with name "Mark" AND a User with name "Matt")
Upvotes: 0
Views: 92
Reputation: 1085
Please try this
Room.joins(:users).where("users.name in (?)", nameArr).group("rooms.id").having("count(distinct users.name)=?", nameArr.count)
Upvotes: 0
Reputation: 118261
You need to do INNER JOIN
to meet the need.
Room.joins(:users).
where(users: { name: ["John", "Mark", "Matt"] } )
Upvotes: 2