John Feminella
John Feminella

Reputation: 311486

How do I fetch distinct joined records in Rails?

I'm using Rails 3.0.10. A Building has_many Floors, and a Floor has_many Suites. I would like to fetch all the Buildings with at least one Suite. (Not every building has suites in it; some are still under construction, for example.)

Some caveats:

What's the best way to go about this using ActiveRecord / ARel / anything else semantic that uses Rails core? I've come up with several different ways of doing this but I'm not sure what's the most canonical.

Upvotes: 0

Views: 132

Answers (1)

BvuRVKyUVlViVIc7
BvuRVKyUVlViVIc7

Reputation: 11811

With 3 Sql-Queries:

Building.where(:id => Floor.where(:id => Suite.all.collect(&:floor_id).uniq).collect(&:building_id))

Upvotes: 1

Related Questions