Sebastián Jara
Sebastián Jara

Reputation: 43

Rails scope filtering elements with no has_many associated elements

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?

Upvotes: 4

Views: 3235

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

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:

Upvotes: 9

Related Questions