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?

4

1 回答 1

3

几个选项...

1)在父级缓存孙子的值(非规范化数据库,添加列并存储属性)。如果只有一个孙子,并且您想在有很多父母的情况下经常显示此值,请执行此操作。

2)你能做一个has_many:通过孙子吗?然后你可以做一个include(:grandchildren). 这可能会节省生成子对象。

3)如果它真的是子孙(has_ones,或belongs_to),您可能会找到一种简单的方法来根据父ID对孙子进行查询(或范围)。然后,您可以运行两个查询,一个获取 parent.all,一个获取 get grandchild.grandchild_of(parents.map(&:id)),然后在 ruby​​ 中循环并将该属性作为属性添加到父级,以供以后循环遍历父级时使用。

4) 最后,执行特定的手工 sql 查询来选择父属性和 grandchild.attribute。该属性将附加到父级并可由 parent.grandchild_attribute_name 访问。 Parent.select('parents.*, grandchild.attribute').joins(:grandchild). 这取决于您的型号,您需要进行试验。

于 2013-05-18T06:06:52.427 回答