我有以下型号:
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 })
类似的问题: