【发布时间】: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) > 0'),它返回了正确的结果。但是当我运行Image.joins(:associated_images).group('images.id').having('count(image_id) = 0') 时,它返回一个空的#<ActiveRecord::Relation []>,我不知道为什么会这样。
我的查询基于Find all records which have a count of an association greater than zero 的讨论
【问题讨论】:
标签: sql ruby-on-rails activerecord