【问题标题】:Rails scope filtering elements with no has_many associated elements没有 has_many 关联元素的 Rails 范围过滤元素
【发布时间】:2015-05-10 17:35:48
【问题描述】:

我有以下型号:

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

我知道我的范围确实效率低下。 我需要另一种方法来获取没有任何关联照片的属性。

有什么帮助吗?

【问题讨论】:

标签: ruby-on-rails ruby activerecord


【解决方案1】:

您可以执行以下操作:

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

类似问题:

【讨论】:

  • 谢谢,反之如何?范围 :has_photo ?
  • 我在答案中添加了范围has_photo,希望对您有所帮助!
  • 还有scope :has_photo, joins(:photos).where.not(photos: {id: nil})
  • @Trip 我将您的建议添加到我的答案中,感谢您保持该帖子的最新状态:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-28
  • 2015-01-27
  • 2014-07-05
  • 1970-01-01
  • 1970-01-01
  • 2014-07-06
相关资源
最近更新 更多