7 Tree Data Structure Plugins for Rails

A surprising number of applications seem to involve storing a tree of similar items out to some arbitrary depth: managers and employees, assemblies and parts, categories for organizing things. Rails doesn't have any native ability to handle a tree structure - but, as with many other things, plugins fill the gap. And even though this requirement has been around for ages, there's still active development in the plugin world as people try to invent a better tree.

The oldest alternative I know of in this are is acts_as_tree, which was actually pulled out of the Rails core code. This plugin established the standards for the genre: it extends ActiveRecord and supplies an API including parent, siblings, ancestors, root, and so on. Succeeding choices have extended this API but remain generally backwards-compatible.

After acts_as_tree came acts_as_nested_set, which provides tree functionality through a different data structure. This plugin optimizes some queries - such as selecting a subtree of descendants - compared to acts_as_tree, and has become a popular alternative. It's also spawned a number of descendants including better_nested_set and awesome_nested_set (which seems to be the most active of the nested set projects). It's worth noting that awesome_nested_set includes STI support.

But that's not the end of the story. Another project, acts_as_materialized_tree, has just put out a release. A materialized tree tags every node with its path. This makes subtree searches more efficient than they are in acts_as_tree, and insertion and removal of children faster than in the nested set plugins. Of course, there are tradeoffs; moving subtrees and counting descendants are not quick with materialized trees.

There are still more choices beyond these three for specialized situations. Two that are worth knowing about are acts_as_category, which combines trees and lists together (and is probably the most heavyweight of the choices here) and acts_as_ordered_tree, which adds a persistent (and arbitrary) sorting to nodes.

It's impossible to recommend a single tree plugin as the best for all circumstances; it depends on the mix of operations in your application. fortunately, the broad API similarity here makes it relatively easy to test the choices and see which one works best for you.

Tweet This Post