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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With