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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…