Blankman
Blankman

Reputation: 266960

How to preload the child collections?

A User has many friends, and each friend has an Address.

I am currently doing this:

User.includes(:friends).find(1)

In my view I am then looping through all of the friends and displaying their address.

Is there a way I can preload the addresses also?

Upvotes: 0

Views: 364

Answers (2)

user3506853
user3506853

Reputation: 814

You can get address by doing this :-

User.includes(friends: :address)

Upvotes: 0

sadaf2605
sadaf2605

Reputation: 7540

According to documentation You can load nested relationships as well by using a Hash like following:

users = User.includes(friends: [:address])

Upvotes: 3

Related Questions