Eager loading with Ancestry ? #80

Sephi-Chan opened this Issue Oct 1, 2011 · 6 comments


None yet
7 participants


I didn't see anything in the documentation or sources about eager loading.

As I plan to use Ancestry to build some kind of forum so it's an important feature to me : being able to eager load the author of each message, and so on.

How do you deal with that ?

Thanks! ;)

andrejj commented Oct 13, 2011

Hi, I think it works fine but I found an issue (and a workaround) regrding the arrange method which builds a hash - tree of the results.

:node - an element of a tree (Node has_ancestry)
:styles - has_and_belongs_to_many association I want to eager load
:position - ordering of children

First try. Should work but it didn't.
tree= node.subtree.arrange(:include=>[:styles], :order=>[:position])
The query which loads associated styles is performed, but all the all the associated styles evaluate to empty arrays.
node.styles -> []

After some digging ancestry's source I managed to make it work:
tree = Node.arrange_nodes(node.subtree.all(:include=>[:styles],:order => "(case when ancestry is null then 0 else 1 end), ancestry, position"))

In conclusion it can be done.

nontone commented Jun 18, 2012

what about doing this with same model.

ie Comment has_ancestry and can have other comments as children? how would you go about doing this?

class Comment < ActiveRecord::Base
has_many :comment_children, class_name: 'Comment', foreign_key: 'ancestry'



stefankroes commented Oct 8, 2014

All ancestry methods like subtree or descendants are just where clauses. You can chain any includes on joins call on them.

There is a solution for eager loading in this Gem:

Which is not depended on the hight of the tree.
It should work with Ancestry Gem

marnen commented Aug 12, 2015


All ancestry methods like subtree or descendants are just where clauses.

That's irrelevant, isn't it? Rails eager loading needs an association name, not a where clause, and Ancestry doesn't appear to implement children as an association.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment