pre-load second level association?

Let's say I have Customer -> Invoice -> OrderItem. All of those are one-to-many.

Is there any way I can tell ActiveRecord than when I access some_customer.invoices, AR should pre-load all the invoice.order_items too, in one query, using a join? Similar to if I issued an :include directive in a #find, but I'm not doing a manual find, I'm just accesing some_customer.invoice. I want AR to automatically pre-load all of the invoice's order_items every time any code accesses some_customer.invoice.

Is this something AR can do? If not, is there a common workaround to get this efficiency? Is there a callback hook for after the customer.invoices are loaded?

Thanks for any advice!

Jonathan

Let's say I have Customer -> Invoice -> OrderItem. All of those are one-to-many.

Is there any way I can tell ActiveRecord than when I access some_customer.invoices, AR should pre-load all the invoice.order_items too, in one query, using a join? Similar to if I issued an :include directive in a #find, but I'm not doing a manual find, I'm just accesing some_customer.invoice. I want AR to automatically pre-load all of the invoice's order_items every time any code accesses some_customer.invoice.

you can say has_many :foos, :include => :bars

Fred

Jonathan Rochkind wrote:

Let's say I have Customer -> Invoice -> OrderItem. All of those are one-to-many.

Is there any way I can tell ActiveRecord than when I access some_customer.invoices, AR should pre-load all the invoice.order_items too, in one query, using a join? Similar to if I issued an :include directive in a #find, but I'm not doing a manual find, I'm just accesing some_customer.invoice. I want AR to automatically pre-load all of the invoice's order_items every time any code accesses some_customer.invoice.

Is this something AR can do? If not, is there a common workaround to get this efficiency? Is there a callback hook for after the customer.invoices are loaded?

Thanks for any advice!

Jonathan    in your Customer class...

has_many :invoices, :include => :order_items

Now, whenever you have @costumer, and you call @customer.invoices, then the order_items will be eagerly loaded. You're probably going to do something more like @customer.invoices.find(params[:id]), and the above will work with that too.