Eager loading with Ancestry ? #80

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

Projects

None yet

7 participants

@Sephi-Chan

Hi,

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

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

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?

@siraz-provectus

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

Comment.roots.eager_load(:comment_children)

@stefankroes
Owner

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

@AlexStanovsky

There is a solution for eager loading in this Gem:
https://github.com/Natural-Intelligence/index_tree

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

@marnen

@stefankroes:

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