Ember Data: Saving relationships

ember-data, ember.js, json

Solution

I needed a deep object, instead of a side-loaded one, so based on kingpin2k's answer, I came up with this:

DS.JSONSerializer.reopen({
    serializeHasMany: function(record, json, relationship) {
        var key = relationship.key,
            property = Ember.get(record, key),
            relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship);

        if (property && relationshipType === 'manyToNone' || relationshipType === 'manyToMany' ||
            relationshipType === 'manyToOne') {

            // Add each serialized nested object
            json[key] = [];
            property.forEach(function(item, index){
                json[key].push(item.serialize());
            });
        }
    }
});

Now when you call `child.serialize()`, it will return this object:

{
  child: {
    name: "Herbert",
    toys: [
      {
        name: 'Kazoo'
      }
    ]
  }
}

Which is what I need. Here's the jsfiddle with it in action: http://jsfiddle.net/jgillick/LNXyp/8/

Problem

I need to save a deep object to the server all at once and haven't been able to find any examples online that use the latest ember data (1.0.0-beta.4). For example, with these models: (jsfiddle) ``` App.Child = DS.Model.extend({ name: DS.attr('string'), age: DS.attr('number'), toys: DS.hasMany('toy', {async:true, embedded:'always'}), }); App.Toy = DS.Model.extend({ name: DS.attr('string'), child: DS.belongsTo('child') }); ``` And this code: ``` actions: { save: function(){ var store = this.get('store'), child, toy; child = store.createRecord('child', { name: 'Herbert' }); toy = store.createRecord('toy', { name: 'Kazoo' }); child.set('toys', [toy]); child.save(); } } ``` It only saves the JSON for the child object but not any of the toys -- not even side loaded: ``` { child: { age: null name: "Herbert" } } ``` Do I have to manually save the toys too? Is there anyway that I can have it send the following JSON to the server: ``` { child: { age: null name: "Herbert", toys: [{ name: "Kazoo" }] } } ``` Or ``` { child: { age: null name: "Herbert", toys: [1] } } ``` See JSFiddle: http://jsfiddle.net/jgillick/LNXyp/2/

Original source