简体   繁体   中英

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. 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.

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. 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.

So ensure that you have properly set the type column to the correct value (`"Image" in your case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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