Hello: Does anyone have a solution to convert an acts_as_tree model to json that includes all its nodes? I trued using :include=>:children, but that only goes down to one single level. Any idea how to iterate the whole tree?
2 Answers
You could write your own method that returns all descendants, however this is one of those cases where the type of tree that you are using is going to be pretty inefficient.
If you are worried about performance and database hits, you should look into one of the nested set gems, or the ancestry gem which are much more efficient ways to fetch tree branches.

- 17,702
- 4
- 51
- 54
Use a helper (or private method) which is recursive and turns your nested models in to a nested hash, then use to_json
to generate a json string.
I needed to generate Json in a HTML/Erb view, but the same idea should apply if you need to generate it from a controller action, or use an Erb template to generate Json. I also needed a (hardcoded) root node, you can skip that if its not required.
categories.html.erb
<script type="text/javascript">
$(function(){
var json = {
id: "node00",
name: "New Pathway",
data: {},
children:
<%= @categories.select { |c| c.root? && !c.leaf? }.collect { |c| category_to_spacetree_json(c) }.to_json.html_safe %>
};
init(json);
});
</script>
categories_helper.rb
def category_to_spacetree_json(category)
hash = {
:id => category.id,
:name => category.name,
:data => '',
:children => []
}
unless category.leaf?
hash[:children] = category.children.public.collect { |c| category_to_spacetree_json(c) }
end
hash
end

- 19,188
- 9
- 91
- 111