Here is the code I use in a Ruby on Rails project to find residences
which have amenities
with the ids
48, 49 and 50. They are connected with a has_many through connection.
id_list = [48, 49, 50]
Residence.joins(:listed_amenities).
where(listed_amenities: {amenity_id: id_list}).
group('residences.id').
having("count(listed_amenities.*) = ?", id_list.size)
The resulting SQL:
SELECT "residences".*
FROM "residences"
INNER JOIN "listed_amenities" ON "listed_amenities"."residence_id" = "residences"."id"
WHERE "listed_amenities"."amenity_id" IN (48, 49, 50)
GROUP BY residences.id
HAVING count(listed_amenities.*) = 3
I'm interested in the number of residences
that result from this query. Is there a way to add a count
or something else to let the database do that calculation? I don't want to waste computing power by doing it in Ruby. Adding a .count
method doesn't work. It results in {528747=>3, 529004=>3, 529058=>3}
.