Ruby on rails 检查模型是否具有嵌套模型连接
我有三种型号:Ruby on rails 检查模型是否具有嵌套模型连接,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我有三种型号:系列,产品和图库。不是每个产品都有图库。我怎么找到那些 这就是我带来的: 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?
系列
,产品
和图库
。不是每个产品都有图库。我怎么找到那些
这就是我带来的:
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
要在一个查询中获得“没有库的所有产品”,可以使用以下代码行
Product.includes(:galleries)。where(galleries:{id:nil})
不确定,但可能类似于Collection.includes(products:[:galleries])。where(galleries:{id:nil})
您能编辑您的问题并添加模型之间的关系吗?可能类似于Product.includes(:galleries)。where(图库:{id:nil})
用模型关系更新了帖子。@Mtihc,出于一些愚蠢的原因,我误读了你的评论。他们两个都错了。并且浪费了更多的时间在搜索答案上。我很抱歉失明,谢谢你!这正是我想要的。你不把它作为答案发布吗?
class Collection
has_many :products
end
class Product
belongs_to :collection
has_many :galleries
end
class Gallery
belongs_to :product
end