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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Rails范围过滤元素没有has_many关联元素相关的知识,希望对你有一定的参考价值。

我有以下型号:

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

类似的问题:

以上是关于Rails范围过滤元素没有has_many关联元素的主要内容,如果未能解决你的问题,请参考以下文章