Matthew Lee
Matthew Lee

Reputation: 3

ActiveRecord query Model by Association attributes

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

Answers (2)

Kh Ammad
Kh Ammad

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

Arup Rakshit
Arup Rakshit

Reputation: 118261

You need to do INNER JOIN to meet the need.

Room.joins(:users).
    where(users: { name:  ["John", "Mark", "Matt"] } )

Upvotes: 2

Related Questions