在 rails 4 中获取空 has_many 记录的 STI 记录

Fetch records in STI for empty has_many records in rails 4

我有一个模型库 has_many :images, as: :imageable, dependent: :destroy 和图像模型 belongs_to :imageable, polymorphic: true。这里使用了单一 Table 继承。现在我想获取并隐藏没有关联图像的画廊。怎么办?

试试这个

Gallery.all.each do |gallery|
   galleries << gallery if (gallery.images.empty?)
end

如果您只想最有效地获取关联为空的所有画廊,您可以使用此范围:

# in Gallery.rb

scope :no_images, -> {
  joins('LEFT OUTER JOIN images ON images.imageable_id = galleries.id).
  group('galleries.id').
  having('count(imageable_id) = 0') }

运行 Gallery.no_images 将 return 所有 Gallery 没有关联图像的对象。

请注意,文档中有以下关于使用单 Table 继承的多态关联的说明:

Using polymorphic associations in combination with single table inheritance (STI) is a little tricky. In order for the associations to work as expected, ensure that you store the base model for the STI models in the type column of the polymorphic association. To continue with the asset example above, suppose there are guest posts and member posts that use the posts table for STI. In this case, there must be a type column in the posts table.

因此请确保您已将 type 列正确设置为正确的值(在您的情况下为 `"Image")。