Ember数据:保存关系 [英] Ember Data: Saving relationships

查看:94
本文介绍了Ember数据:保存关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一次将深层对象保存到服务器,并且无法在线查找使用最新的ember数据(1.0.0-beta.4)的任何示例。

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).

例如,使用这些模型:
jsfiddle

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')
});

此代码:

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();
    }
}  

它只保存子对象的JSON,但不保存任何玩具 - 甚至没有装载:

It only saves the JSON for the child object but not any of the toys -- not even side loaded:

{
  child: {
    age: null
    name: "Herbert"
  }
}

还要手动保存玩具吗?有没有,我可以把它发送以下的JSON到服务器:

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"
    }]
  }
}

{
  child: {
    age: null
    name: "Herbert",
    toys: [1]
  }
}

请参阅JSFiddle: http ://jsfiddle.net/jgillick/LNXyp/2/

See JSFiddle: http://jsfiddle.net/jgillick/LNXyp/2/

推荐答案

我需要一个深层的对象,而不是一个侧装的,所以基于kingpin2k的答案,我想出了这一点:

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());
            });
        }
    }
});

现在,当您调用 child.serialize(),它将返回此对象:

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

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

我需要什么这是jsfiddle的行动: http://jsfiddle.net/jgillick/LNXyp/8/

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

这篇关于Ember数据:保存关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆