Nested :include ActiveRecord option June 23, 2007
Posted by Slobodan Kovacevic in : Programming, Ruby & Rails , add a commentWhile working on a site I had User, Order, OrderItems and Product models and they were related like this:
Order belongs_to User
Order has_many OrderItems
OrderItem belongs_to Product
So, when displaying an order I found myself doing accessing product through order_item, i.e. @order.order_items.product.name.
Although this worked problem was that even though I have told Rails using :include to eager load order_items it didn’t load products, so whenever I accessed a product it executed a separate SQL query. In other words, to display order with 10 products it required 11 SQL queries - hardly optimized.
Rails API documentation doesn’t say anything about eager loading “second” level, but after some searching I found that you can do that you can do nested :includes, like this:
This will eager load User and OrderItems, but it will also eager load Products under each OrderItem. This decreased my number of queries from 11 for 10 product order to only one (big one).
You can read more (for example, it appears that you can nest multiple :includes) about this undocumented feature in ‘The beauty of a nested ‘:include’ option’.