0

In Rails, I'm trying to eager load something to speed it up. I've got a Parent-Child-Grandchild situation, but only need the Parent and an attribute of the Grandchild. If I...

Parent.all.includes(:child => :grandchild)

then Bullet gripes about an unused eager load of the child (which is true, I don't need it). Is there an easier way to have access to the Parent record and Grandchild.some_attribute?

robertmiles3
  • 899
  • 10
  • 20

1 Answers1

3

A couple options...

1) Cache the value of the grand-child (denormalize the db, add a column and store the attribute) on the parent. Do this if there is only one grandchild and you want to frequently show this value in a situation where you have many parents.

2) can you do a has_many :through on the grandchildren? Then you can just do an include(:grandchildren). That may save generating the child objects.

3) If it really is child and grandchild (has_ones, or belongs_to), you can probably find a simple way to do a query (or scope) on grandchild based on the parent id. You can then run two queries, one to get parent.all, one to get grandchild.grandchild_of(parents.map(&:id)), and then loop in ruby and add the attribute to the parent as a attribute, ready for use when you loop through the parents later.

4) Lastly, do a specific, hand worked sql query to select the parent attributes and the grandchild.attribute. The attribute will be attached to the parent and accessible by parent.grandchild_attribute_name. Parent.select('parents.*, grandchild.attribute').joins(:grandchild). This you'll need to experiment with, depending on your model.

Mark Swardstrom
  • 17,217
  • 6
  • 62
  • 70