Greedy Loading

Found via http://www.updrift.com/article/questions-ruby-on-rails-skeptics-ask.

>

`for order in Order.find(:all)
puts “Item ordered: #{order.line_item.product_id}
puts “Description: #{order.line_item.product.description}
end`

In this example, there would be one database call for the main order, then two calls to retrieve the line item information then the product description. Here’s a much better approach.

`for order in Order.find(:all, :include => [:line_items, :product])
puts “Item ordered: #{order.line_item.product_id}
puts “Description: #{order.line_item.product.description}
end`

Very similar code, but in the latter version the :include attribute tells Rails to preload the line items and products, so it loads up everything in one database call rather than multiple ones. You also have the option of using the find_by_sql function to specify your own custom call.