Ember Data: Saving relationships

后端 未结 3 469
时光说笑
时光说笑 2020-12-28 20:11

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,

3条回答
  •  一生所求
    2020-12-28 20:50

    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/

提交回复
热议问题