我有以下模型:
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 })
类似问题:
关于ruby-on-rails - 没有 has_many 关联元素的 Rails 作用域过滤元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28944106/