12

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/

Jeremy Gillick
  • 2,560
  • 3
  • 27
  • 35

3 Answers3

9

The answers here are out of date. Ember Data now supports embedded records, which allows you to do exactly what you're looking to do, which is to get and send the full object graph in one big payload. For example, if your models are set up like this:

App.Child = DS.Model.extend({
    name: DS.attr('string'),
    age: DS.attr('number'),
    toys: DS.hasMany('toy')
});
App.Toy = DS.Model.extend({
    name: DS.attr('string'),
    child: DS.belongsTo('child')
});

You can define a custom serializer for your Child model:

App.ChildSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    toys: {embedded: 'always'}
  }
});

This tells Ember Data that you'd like 'toys' to be included as part of the 'child' payload. Your HTTP GET response from your API should look like this:

{
  "child": {
    "id": 1,
    "name": "Todd Smith",
    "age": 5,
    "toys": [
      {"id": 1, "name": "boat"},
      {"id": 2, "name": "truck"}
    ]
  }
}

And when you save your model, Ember Data will send this to the server:

{  
   "child":{  
      "name":"Todd Smith",
      "age":5,
      "toys":[  
         {  
            "id":"1",
            "name":"boat",
            "child":"1"
         },
         {  
            "id":"2",
            "name":"truck",
            "child":"1"
         }
      ]
   }
}

Here is a JSBin that demonstrates this.

http://emberjs.jsbin.com/cufaxe/3/edit?html,js,output

In the JSbin, when you click the 'Save' button, you'll need to use the Dev Inspector to view the request that's sent to the server.

Johnny Oshika
  • 54,741
  • 40
  • 181
  • 275
  • Do you know if this is the preferred method? My understanding is that including embedded records in your GET responses is not always the most efficient. I can however see the benefits of embedding records in making POST/PUT requests. – antony Jan 28 '15 at 05:08
  • 1
    @antony, you're asking an API design question which is not specifically about Ember Data. If you believe in aggregates (e.g. order has order items, but order items on their own don't have identity), then you'll want to use embedded records. Also, if you need updates to happen in one atomic transaction (e.g. order and order items again), then you'll want to use embedded records. If, however, every model can have its own identifiable endpoint, then embedded records doesn't make sense. – Johnny Oshika Jan 28 '15 at 17:56
3

toys can't be both async and embedded always, those are contradicting options. Embedded only exists on the active model serializer currently.

toys: DS.hasMany('toy', {embedded:'always'})

the toys are a ManyToOne relationship, and since the relationship exists on the belongsTo side it is more efficient to save the relationship during the toy's save. That being said, if you are creating it all at once, then want to save it in one big chunk that's where overriding comes into play.

serializeHasMany: function(record, json, relationship) {
  var key = relationship.key;

  var relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship);

  if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany' ||
      relationshipType === 'manyToOne') {
    json[key] = get(record, key).mapBy('id');
    // TODO support for polymorphic manyToNone and manyToMany relationships
  }
 },

And your save should be like this

    var store = this.get('store'),
        child, toy;

    child = store.createRecord('child', {
        name: 'Herbert'
    });
    toy = store.createRecord('toy', {
        name: 'Kazoo'
    });

    child.get('toys').pushObject(toy);
    child.save().then(function(){
       toy.save();
    },
    function(err){
      alert('error', err);
    });
Kingpin2k
  • 47,277
  • 10
  • 78
  • 96
  • Where is `toys` defined? On the line where you call: `toys.save()` And if you meant `child.get('toys').save()`, or to access the response of the promise, does that call save on each of the indifidual models or save them all at once? I have the same problem as Jeremy and when I try to debug/inspect the hasMany property, like in this case look at child.get('toys') even just after I pushed a new record there, the valueds in the array are null. I assumed this was because Ember-Data knows to store the id of the toy in the toys array, but the toy doesn't have an id yet because it wasn't saved. – Matt Mazzola Jan 20 '14 at 02:54
  • Yes, that should be `toy`, I was saving the individual toy. – Kingpin2k Jan 20 '14 at 03:05
  • So if I understand this properly. We have setup models with mutal One-to-many relationship, Child hasMany Toys, and Toy belongsTo Child. Internally there will be a `childId` property on the toy model which is what will actually be persisted. When you call `child.pushObject(toy)` the relationship between the two is established and once child is saved, the toy's childId property is automatically updated? I was expecting you to have to call `toy.set('child', response)` inside the promise fulfillment handler. – Matt Mazzola Jan 20 '14 at 03:42
0

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/

Jeremy Gillick
  • 2,560
  • 3
  • 27
  • 35
  • Using Ember 1.3.1/data 1.0.0-beta 6, `property = Ember.get(record, key)` appears to return an empty promise array. It's particularly strange because I can access the child records with `record.get('key').then(function(items){...})`. Any idea if this is a known issue? – eriknelson Feb 08 '14 at 22:44