2017-03-16 13 views
0

私はモデルがCollectionProductGalleryの3モデルです。すべての製品にギャラリーがあるわけではありません。どのようにそれらを見つけるのですか?モデルにネストされたモデルの接続があるかどうかをチェック

Collection.find_each do |collection| 
    collection.products.each do |product| 
    next if collection.products.empty? 
    puts "Product #{product.id} does not have gallery" unless product.galleries.present? 
    end 
end 

それは、クエリのトンを送るので、これは、悪い方法である:

これは私がして来たものです。それをどうすれば改善できますか?

Upd。

class Collection  
    has_many :products 
end 

class Product  
    belongs_to :collection 
    has_many :galleries 
end 

class Gallery  
    belongs_to :product 
end 
+0

わからないのこのラインを使用しますが、多分これ 'Collection.includes(製品のようなものができ(ギャラリー:{id:nil}) ' – Mtihc

+0

質問を編集してモデル間の関係を追加できますか? – Jeremie

+0

おそらく 'Product.includes(:galleries).where(gallery:{id:nil})'のようなものでしょうか? – Mtihc

答えて

1

1つのクエリで「ギャラリーせずにすべての製品を」取得するには、コード

Product.includes(:galleries).where(galleries: {id: nil})

関連する問題