I’ve just built a acts_as_tree model,
now I need to render it out as a tree structure in view.
and I also need a action method to loop through every row of the
database following the tree structure ( from root to it’s branch, then
to the ends of the branch, then go back for other branches…). I think
both the view helper and action method need to use a similar loop style,
and this code may be popular, at lease useful. Is there any article
about this subject?
I’ve just built a acts_as_tree model,
now I need to render it out as a tree structure in view.
and I also need a action method to loop through every row …
The word “loop” may be leading you in the wrong direction. If
you hear the words “tree” or “hierarchy”, you should be looking
at recursive solutions. So, in pseudo-ruby:
walk - level is either an item or a tree of items
def walk(level)
if level.is_leaf?
# handle leaf action
else
# handle branch pre-action
level.each { |item| walk(item) }
# handle branch post-action
end
end
In my (limited) experience, recursive code tends to be very
small and simple, once written. Writing it, however, can be
challenging, in that it requires a different way of thinking
than iterative code does.
There are also tree-walk routines that will simply allow you
to iterate through the nodes of a tree. Whether there is a
routine such as this for your particular tree, I don’t know.