Here is my model:
class Project < ActiveRecord::Base
belongs_to :parent, :foreign_key => :project_id, :class_name => "Project"
has_many :children, :dependent => :destroy, :class_name => "Project", :foreign_key => :project_id
Check out this jquery tree plugin with a JSON data example:
$(function () {
$("#demo2").jstree({
"json_data" : {
"ajax" : {
"url" : "/static/v.1.0pre/_docs/_json_data.json",
"data" : function (n) {
return { id : n.attr ? n.attr("id") : 0 };
}
}
},
"plugins" : [ "themes", "json_data" ]
});
});
The basic structure for supplying data in JSON format looks like this:
{
"data" : {
"title" : "The node title",
// Leave out `attr` if unnecessary; the `attr` object will be passed to the jQuery `attr` function
"attr" : { "id" : "node_identificator", "some-other-attribute" : "attribute_value" } },
// Use `state` and `children` for NON-leaf nodes only
"state" : "closed", // or "open", defaults to "closed"
"children" : [ /* array of child nodes objects */ ]
}
I aim to dynamically create a jstree for a collection of projects. This collection can include children, each with their own children, and so on. My controller already responds to JSON, and I currently have code in the view to build the tree.
I have tested using this JSON data example, and it successfully generates the desired tree structure:
{
"data" : {
"title" : "Projects",
"attr" : { "href" : "/projects" } },
"children" : [ {
"data" : {
"title" : "test",
"attr" : { "href" : "/projects/7" , "class" : "selected" } },
"state" : "open" ,
"children" : [ {
"data" : {
"title" : "test_1",
"attr" : { "href" : "/projects/9" } },
"children" : [ ] }
] } , {
"data" : {
"title" : "test1",
"attr" : { "href" : "/projects/8" } },
"children" : [ ] }
], "state" : "open" }
I am looking for suggestions on how to automatically generate JSON data for my project collection following the schema provided above. Any ideas?