Andrew Andrew - 1 year ago 96
SQL Question

Rails find record with zero has_many records associated

This seems fairly simple but I can't get it to turn up on Google.

If I have:

class City < ActiveRecord::Base
has_many :photos

class Photo < ActiveRecord::Base
belongs_to :city

I want to find all cities that have no photos. I'd love to be able to call something like...

City.where( photos.empty? )

...but that doesn't exist. So, how do you do this kind of query?

Having now found an answer to the original question, I'm curious, how do you construct the inverse?

IE: if I wanted to create these as scopes:

scope :without_photos, includes(:photos).where( :photos => {:city_id=>nil} )
scope :with_photos, ???

Answer Source

Bah, found it here:

City.includes(:photos).where(photos: { city_id: nil })
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download