我有以下型号:
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
我知道我的范围确实很低效。我需要另一种方式来获取没有与之关联的照片的属性。
有什么帮助吗?
您可以执行以下操作:
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 })
类似问题:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句