【问题标题】:Find all records which have a count of an association of zero and none-zero查找所有关联计数为零和非零的记录
【发布时间】:2020-08-07 06:01:46
【问题描述】:
class Gallery < ApplicationRecord
  has_many :associated_images, as: :imageable
end

class Event < ApplicationRecord
  has_many :associated_images, as: :imageable
end

class Image < ApplicationRecord
  has_many :associated_images
end

class AssociatedImage < ApplicationRecord
  belongs_to :imageable, polymorphic: true
  belongs_to :image
end

我想获取所有正在使用的图像,以及一个不同的查询来获取所有未使用的图像(基于AssociatedImage)。

我尝试了Image.joins(:associated_images).group('images.id').having('count(image_id) &gt; 0'),它返回了正确的结果。但是当我运行Image.joins(:associated_images).group('images.id').having('count(image_id) = 0') 时,它返回一个空的#&lt;ActiveRecord::Relation []&gt;,我不知道为什么会这样。

我的查询基于Find all records which have a count of an association greater than zero 的讨论

【问题讨论】:

    标签: sql ruby-on-rails activerecord


    【解决方案1】:

    原因是在 SQL 中,当没有行时计数为零。所以如果没有行,甚至没有组,就没有结果。

    你想要的是

    Image.left_joins(:associated_images).where(associated_images: {id: nil}).group('images.id')
    

    当 SQL 进行左连接时,对于没有关联图像的图像,它会为 associated_images 表中的所有列填充 NULL。所以associated_images.id 为 nil 的就是我们想要的。

    【讨论】:

      猜你喜欢
      • 2013-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      • 1970-01-01
      • 2011-10-23
      相关资源
      最近更新 更多