Thursday, February 21, 2008

Massage Rails better_nested_set full_set into a hierarchy - JSON

better_nested_set is a great Rails plugin for working with certain types of hierarchical data. The typical example where better_nested_set is used is for a threaded message board. better_nested_set will allow you to pull in a message and all its descendants with a single full_set call. The data that is returned includes a level field that allows you to indent the messages to indicate the appropriate parental relationships.

Sometimes, however, it may be necessary to take that full_set and turn it into a hierarchical data structure. For example when working with Ext JS you may want to feed this data to a tree control that needs a hierarchical JSON representation of the data. Here is some sample code that will do the necessary data massaging: