Eager loading in "both directions"
Eager loading does not work as I expect.
I have Products that has_many Variants,开发者_如何学Python and of course each Variant belongs_to a Product.
I use code like this to load a product and all its variants:
products = Product.includes(:variants)
This works: all products and all variants are loaded with only two queries. However, the product of each variant is not loaded, so the following code causes another SQL-query:
puts products[0].variants[0].product.title
Why is that, and how can I fix it? I suppose Product.includes(:variants => :product)
would work, but it causes one extra big and unnecessary SQL-query, since the Product-data is already available.
Active Record will only eager loading an association on the level you've specified. In its point of view, variant.product
will be treated as another level of association. So, if you want to eager loading it, you'd have to do:
products = Product.includes({:variants => :product})
精彩评论