title: using JSON in Rails, Backbone and Mustache - formats seem to differ
body: <p>I am trying to put together a Rails app, with backbone.js and mustache templating. I am finding that the JSON required by backbone isn't compatible with the JSON required by Mustache. (I started out following this tutorial <a href="http://www.jamesyu.org/2011/01/27/cloudedit-a-backbone-js-tutorial-by-example/" rel="nofollow">Cloudedit -a backbone.js tutorial by example</a>, but I want to use Mustache where he is using JST.</p>
  
  <p>For backbone we must set ActiveRecord::Base.include_root_in_json = false. For my model (person with firstname and surname) the data sent by rails from /people looks like this:</p>
  
  <pre><code>[{"firstname":"Jane","surname":"Jones"},{"firstname":"Janet","surname":"Jensen"}]
  </code></pre>
  
  <p>My mustache template looks like this:</p>
  
  <pre><code>&lt;h3&gt;&lt;a href='#new'&gt;Create New&lt;/a&gt;&lt;/h3&gt;
  &lt;h4&gt;People&lt;/h4&gt;
  &lt;ul&gt;
  {{#people}}
  &lt;li&gt;{{firstname}} {{surname}}&lt;/li&gt;
  {{/people}}
  &lt;/ul&gt;
  </code></pre>
  
  <p>and from the mustache docs I expect that what it wants to see is</p>
  
  <pre><code>{"people":[{"firstname":"Jane","surname":"Jones"},{"firstname":"Janet","surname":"Jensen"}]}
  </code></pre>
  
  <p><em>Edited out me transforming the JS collection back to JSON and sending to Mustache. 
  Don't need to do that. Mustache.js expects to see js objects, not strings of JSON.</em></p>
  
  <p>By the time I get to Mustache.to_html I have a backbone collection of models. The models have the attributes <em>firstname</em> and <em>surname</em>. It looks like this in firebug:</p>
  
  <pre><code>collection
    +_byCid
    +_byId
     length 2
    - models  [object { attributes=(...), more...}, object {attributes=(...), more...}]
      - 0 object { attributes=(...), more...}
        ....... some more properties of the object
          + attributes object {firstname="Janet", surname="Jensen"}
  </code></pre>
  
  <p>There seem to be a couple of problems here. 
  1. There is no mention of the name of the collection (people). I can get around that in various ways I guess, at least by using {{#models}}..{{/models}} in the template.</p>
  
  <ol>
  <li>The attributes are buried deeper than Mustache.js looks. When it gets down to trying to find the 'firstname' tag in the object, it looks for object['firstname'] and doesn't find it, but object.attributes['firstname'] has the correct value.</li>
  </ol>
  
  <p>It seems I'm all mixed up here....So what am I doing wrong? And how can I fix it?</p>