Reputation: 28164
Consider a typical relational structure:
Answer has many comments. comments belongs to a user, and have many likers
answers.to_json(:include => {:comments => {:include => :user, :likers}})
If i call to_json , it will perform the database retrievals one by one for individual user in individual comments.
The much more efficient solution would be to put the required ids for each type in an array, do 3 database calls to retrieve them, put it into a hash, and construct the json according to the hash.
This seems like a pretty common use case. I am thinking of writing my own recursive function for this, but if anyone can point me to something that has already been done, that will be great!
** i am using mongoid / mongodb, i am not sure if it works the same way in active record.
Upvotes: 0
Views: 372
Reputation: 65877
May be you can try mongoid eager loading, then you can query mongo just like AR eager loading
Answer.includes(:comments, :likers)
The patch is still not included in the mongoid master branch, but you can download it as a independednt gem from here
Read this pull request for more info
Upvotes: 2