Get updates

Scott Displaying a hierarchy and acts_as_tree

What’s brewing over at ListFinity, home of infinite lists?

Well, supposedly right now I’m working out various means of constructing and manipulating “infinitely nestable” lists, as in an object hierarchy (aka tree view) of arbitrary depth.

That’s all well and good, but not as straightforward to code as the display of a single unordered list. I figured that such a hierarchy would be a good candidate for recursion, and in this case that didn’t sound like too big a chore to write… except when I started to imagine that each loop back to the recursive method would want to pass on the list data for the next loop to walk through another level, etc. This triggered a flash of nightmares where a sufficiently large or deep list (nevermind one mangled to include circular references) spurs the recursion on to eat memory like a mosquito with its proboscis stuck in the jugular.

Then I started reading about acts_as_tree. Hey, hierarchy wiring ready to go! And I had already named a column parent_id in expectation of having to manage a hierarchy all on my own. Now it’s possible to take a plain old table, with a parent_id column, and quickly apply a hierarchy skeleton.

There’s also acts_as_nested_set, which sounds cool but seems to have some issues. Plus better nested set but at this stage that may actually be a bit more than I need. Retrieving an entire set of descendants in one query does sound attractive though.

Back to our simple acts_as_tree model, someone has already put some effort into addressing how to display the tree. I’ll start there and see how it works out.

2 Responses to “Displaying a hierarchy and acts_as_tree”

  1. I’m leary of hardcoding HTML into my helper…I’m sure there is probably an easy way to do this, to get the entire tree and walk it…but I have not discovered it yet.

  2. I agree, Anthony.

    The moment I come across a clean and elegant way to display the tree, I’m sure I’ll post about it.

    In the meantime, with my current project I’ve moved away from a design involving displaying multiple levels/branches of a hierarchy all at once. I may revisit that concept, though right now I’m feeling good about the decision to start with everything collapsed and fetch a single level when an item is expanded.

    I suppose I won’t know whether it’s truly more responsive to load an entire tree up front until I do some testing; both methods have trade-offs but the one-level-at-a-time display is simpler to implement.

Leave a Reply

Fatal error: Call to undefined function show_subscription_checkbox() in /home/dmetro/ on line 90