2017-03-16 34 views
0

我有一個3型號:Collection,ProductGallery。並非每件產品都有畫廊。我如何找到這些?檢查型號是否有嵌套型號連接

這是我想出了:

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(產品:[:galleries])。where(galleries:{id:nil})' – Mtihc

+0

你能編輯你的問題並添加模型之間的關係嗎? – Jeremie

+0

可能是這樣的'Product.includes(:galleries).where(galleries:{id:nil})' – Mtihc

回答

1

得到「所有產品不畫廊」,在一個單一的查詢,您可以使用此行代碼

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