简体   繁体   English

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

[英]Fetch records in STI for empty has_many records in rails 4

I have a model Gallery that has_many :images, as: :imageable, dependent: :destroy and Image model that belongs_to :imageable, polymorphic: true. 我有一个模型库has_many:images,as :: imageable,dependent :: destroy和图像模型belongs_to:imageable,polymorphic:true。 Single Table Inheritance is being used here. 这里使用单表继承。 Now I want to fetch and hide the Galleries which don't have images associated to it. 现在我想获取并隐藏没有与之关联的图像的库。 How to go about it? 怎么去呢?

Try this 尝试这个

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

If you simply want to most effectively fetch all galleries with an empty association, you could use this scope: 如果您只想最有效地获取具有空关联的所有图库,则可以使用此范围:

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

Running Gallery.no_images would return all Gallery objects with no associated images. 运行Gallery.no_images将返回没有关联图像的所有Gallery对象。

Please note that the docs have the following to say about using polymorphic associations with Single Table Inheritance: 请注意,有关使用与单表继承的多态关联的文档有以下说明:

Using polymorphic associations in combination with single table inheritance (STI) is a little tricky. 将多态关联与单表继承(STI)结合使用有点棘手。 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. 为了使关联按预期工作,请确保将STI模型的基本模型存储在多态关联的类型列中。 To continue with the asset example above, suppose there are guest posts and member posts that use the posts table for STI. 要继续上面的资产示例,假设有一些访客帖子和成员帖子使用了STI的posts表。 In this case, there must be a type column in the posts table. 在这种情况下,posts表中必须有一个type列。

So ensure that you have properly set the type column to the correct value (`"Image" in your case). 因此,请确保已将type列正确设置为正确的值(在您的情况下为“Image”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM