Rails范围过滤元素没有has_many关联元素

时间:2015-03-09 14:12:20

标签: ruby-on-rails ruby activerecord

我有以下型号:

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

我知道我的范围非常低效。 我需要另一种方法来获取没有任何相关照片的属性。

任何帮助?

1 个答案:

答案 0 :(得分:5)

您可以执行以下操作:

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 })

类似问题: