Andrew Andrew - 6 months ago 20
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
end

class Photo < ActiveRecord::Base
belongs_to :city
end


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?




Update:
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

Bah, found it here: http://stackoverflow.com/a/5570221/417872

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