Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 751
Sebastián Jara Avatar asked Feb 10 '23 17:02

Sebastián Jara


1 Answers

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:

  • How to query a model based on attribute of another model which belongs to the first model?
  • Rails active record querying association with 'exists'
  • Rails 3, has_one / has_many with lambda condition
  • Join multiple tables with active records
  • Rails 4 scope to find parents with no children
like image 130
MrYoshiji Avatar answered Apr 27 '23 18:04

MrYoshiji