4

I have the following models:

class Property < ActiveRecord::Base
    has_many :photos
    scope :no_photos, -> { where('properties.id NOT IN (SELECT DISTINCT(property_id) FROM photos)') }
end

class Photo < ActiveRecord::Base
    belongs_to :property
end

I know that my scope is really inefficient. I need another way to get the properties that don´t have any photos associated to them.

Any help?

1 Answers1

9

You can do the following:

class Property < ActiveRecord::Base
  has_many :photos
  scope :has_no_photo, includes(:photos).where(photos: { id: nil })
  scope :has_photo, includes(:photos).where('photos.id IS NOT NULL')
  # rails 4 or higher (thanks to @trip)
  scope :has_photo, includes(:photos).where.not(photos: { id: nil })

Similar questions:

MrYoshiji
  • 54,334
  • 13
  • 124
  • 117