At 3:45 AM +0900 4/21/07, Nanyang Zhan wrote:
> 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.

-r
-- 
http://www.cfcl.com/rdm            Rich Morin
http://www.cfcl.com/rdm/resume     rdm / cfcl.com
http://www.cfcl.com/rdm/weblog     +1 650-873-7841

Technical editing and writing, programming, and web development