Rails嵌套N + 1查询问题

时间:2012-11-27 12:36:44

标签: ruby-on-rails

我的协会是这样的:

vendor has shipments  
shipment has order
order has products

在我的控制器中,我写了

@shipments = @vendor.shipments.includes(:order)

但在我看来,我正在使用

shipment.order.products.collect(&:name)

因此它正在返回Rails'bullet'gem

的N + 1查询问题

有人帮我解决嵌套N + 1查询问题吗? 我需要如何在控制器中写入?

1 个答案:

答案 0 :(得分:9)

@shipments = @vendor.shipments.includes(:order => :products)

应该有效。请在此处详细了解http://guides.rubyonrails.org/active_record_querying.html#nested-associations-hash