title: Create jstree in rails with json data using the ajax config option for association parent => children
body: <p>My model is:</p>
  
  <pre><code>class Project &lt; ActiveRecord::Base
      belongs_to :parent, :foreign_key =&gt; :project_id, :class_name =&gt; "Project"
      has_many :children, :dependent =&gt; :destroy, :class_name =&gt; "Project", :foreign_key =&gt; :project_id
  </code></pre>
  
  <p><a href="http://www.jstree.com/" rel="nofollow">jquery tree plugin</a> with json_data example:</p>
  
  <pre><code>$(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" ]
  });
  });
  </code></pre>
  
  <p>and the basic structure to supply data in the json format is:</p>
  
  <pre><code>{ 
      "data" : {
          "title" : "The node title",
  
      // omit `attr` if not needed; the `attr` object gets passed to the jQuery `attr` function
      "attr" : { "id" : "node_identificator", "some-other-attribute" : "attribute_value" } },
      // `state` and `children` are only used for NON-leaf nodes
      "state" : "closed", // or "open", defaults to "closed"
      "children" : [ /* an array of child nodes objects */ ]
  }
  </code></pre>
  
  <p>I want to create the jstree for a collection of projects dynamically. this collection can have childs, and each child childs and so on. my controller already responds to json and in view I have now the code to create the tree.</p>
  
  <p>I test with this json data example and it creates the tree that I want to:</p>
  
  <pre><code>{
  "data" : {
      "title" : "Projectos",
      "attr" : { "href" : "/projects"  } }, 
      "children" : [  { 
          "data" : {
              "title" : "teste",
              "attr" : { "href" : "/projects/7"  , "class" : "selected"  } }, 
              "state" : "open" ,
              "children" : [  { 
                  "data" : { 
                      "title" : "teste_1",
                      "attr" : { "href" : "/projects/9"  } },
                      "children" : [  ] } 
              ] } , { 
  "data" : { 
      "title" : "teste1",
      "attr" : { "href" : "/projects/8"  } }, 
      "children" : [  ] } 
  ], "state" : "open" }
  </code></pre>
  
  <p>I want to generate json data automatically to my collection of projects following the schema example above. Any suggestions?</p>