Andrew Andrew - 9 months ago 44
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, ???


Bah, found it here:

City.includes(:photos).where(photos: { city_id: nil })