In a rails app, i have a 3 models, Room, User and UsersRoom which is an association table between Room and User.
I want to query for a Room related to multiple users.
If i do:
Room.includes(:users_rooms).where(users_rooms: { user_id: user_ids }
I get all the room with at least one users_room containing one users_ids.
I want to get the room with users_rooms present for each user_ids.
Is there a clean way to do this without have to loop on the rooms after querying them ?
2
Answers
I would try the following:
Notes:
COUNT
in theselect
is required because some database engine versions complain when usingCOUNT
in thehaving
without having it defined in theselect
part. You can try to remove that line.join
does aINNER JOIN
between both tables.where
is want you already had.group
groups the found records into a single line and allows usingCOUNT
.having
only returns thoserooms
that had at leastuser_ids.size
users_rooms
associated.I would do:
Creating the indirect assocation is optional but the abstraction makes it so that your query isn’t bound to how the join table is implemented.
For example
UsersRoom
isn’t a great name and you might want to call it something more fitting likeBooking
– this lets you do that without breaking anything.