Ember 数据:保存关系 [英] Ember Data: Saving relationships
问题描述
我需要一次性将一个深层对象保存到服务器,但在网上找不到任何使用最新 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/
推荐答案
我需要一个深对象,而不是一个侧载对象,所以基于 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屋!