title: Why is Backbone model sending duplicate attributes to server on save?
body: <p>I'm writing a practice Backbone app, with Rails backend API, and I'm confused about the behavior of save on Backbone models.</p>
  
  <p>Let's say a Team has many Players, and I want to save a team with numerous players in a single POST.</p>
  
  <p>So in Rails I have:</p>
  
  <pre><code>class Team &lt; ActiveRecord::Base
    has_many :players
    accepts_nested_attributes_for :players
  end
  
  class Player &lt; ActiveRecod::Base
    belongs_to :team
  end
  </code></pre>
  
  <p>and for backbone client, I have a Player model and a Players collection defined (not shown)</p>
  
  <p>and then the containing Team model (NOTE: no Teams collection)</p>
  
  <pre><code>Demo.Models.Team = Backbone.Model.extend({
    urlRoot: '/teams',
    defaults: {
      'team_size': 12
    },
    initialize: function() {
      this.players = new Demo.Collections.Players());
    },
    toJSON: function() {
      var json = _.clone(this.attributes);
      json.players_attributes = this.players.map(function(player) {
        return player.toJSON();
      });
      return json;  
    }
  }
  </code></pre>
  
  <p>When I examine my stringified JSON in the browser, everything looks good:</p>
  
  <pre><code>{"team_size":12, "players_attributes":[{"name":"Fred"},{"name":"Jim" },{"name":"Mark"}]}
  </code></pre>
  
  <p>Checking the server logs, the lone top level attribute ('team size') is repeated, once at the top level, and then repeated under a root key.</p>
  
  <pre><code>Started POST "/teams" for 127.0.0.1 at 2012-06-07 13:39:40 -0400
  Processing by TeamsController#create as JSON
    Parameters: {
      "team_size"=&gt;12, "players_attributes":[{"name":"Fred"},{"name":"Jim" },{"name":"Mark"}]}, 
      "team"=&gt;{"team_size"=&gt;12}
    }
  </code></pre>
  
  <p>I have a few questions:</p>
  
  <ol>
  <li><p>What's the best way to ensure the player_attributes are nested inside the root key? I (So that I can do a nested save inside TeamController, in the standard rails manner: (i.e. Team.create(params[:team]) )  I can accomplish this with some javascript hackery inside toJSON, but I'm guessing there's an easier, cleaner way.</p></li>
  <li><p>Is this standard, desirable behaviour? To send duplicates of attributes like this? I guess there's no harm, but it doesn't smell right.</p></li>
  <li><p>Am I not defining the url / urlRoot correctly or some such?</p></li>
  </ol>
  
  <p>thanks</p>