Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember Data: Saving relationships

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/

like image 668
Jeremy Gillick Avatar asked Dec 21 '13 02:12

Jeremy Gillick


2 Answers

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.

like image 142
Johnny Oshika Avatar answered Nov 15 '22 11:11

Johnny Oshika


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);
    });
like image 33
Kingpin2k Avatar answered Nov 15 '22 10:11

Kingpin2k