Acts_as_nested_set ActiveRecord with mx:Tree

Posted by Daniel Wanja on 11/23/2007 ActiveRecord: app/models/category.rb
app/models/category.rb
class Category < ActiveRecord::Base
  acts_as_nested_set
end
Controller: app/controllers/categories_controller.rb
app/controllers/categories_controller.rb
class CategoriesController < ApplicationController
  def index
     Category.result_to_attributes_xml(Category.root.full_set)
  end
end
Flex Application: ActsAsNestedSet.mxml
ActsAsNestedSet.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    layout="vertical"
    applicationComplete="categories.send()">
<mx:HTTPService id="categories" url="http://localhost:3000/categories" resultFormat="e4x" />
<mx:Tree dataProvider="{categories.lastResult}" 
    labelField="@name"
    width="100%" height="100%" />    
</mx:Application>

Result: 20071123_categories.jpg

XML generated by Category.result_to_attributes_xml(Category.root.full_set):
XML generated by Category.result_to_attributes_xml(Category.root.full_set)
<node name="Main Category" id="15" description="">
  <node name="Cameras &amp; Photo" id="16" description="">
    <node name="Bags" id="17" description=""/>
    <node name="Accessories" id="18" description=""/>
    <node name="Analog Cameras" id="19" description=""/>
    <node name="Digital Cameras" id="20" description=""/>
  </node>
  <node name="Cell Phones" id="21" description="">
    <node name="Accessories" id="22" description=""/>
    <node name="Phones" id="23" description=""/>
    <node name="Prepaid Cards" id="24" description=""/>
  </node>
  <node name="Dvds" id="25" description="">
    <node name="Blueray" id="26" description=""/>
    <node name="HD DVD" id="27" description=""/>
    <node name="DVD" id="28" description=""/>
  </node>
</node>

I used the http://wiki.rubyonrails.org/rails/pages/BetterNestedSet plugin.

Too cool!

UPDATE: The BetterNestedSet plugin doesn’t work out of the box with Rails 2.0 RC1. Thanks Joel for that info. Read more in the comment of this blog entry.

UPDATE2: Thanks Fabien, BetterNestedSet now works with Rails 2.0!