在related question中我想知道如何在 ember.js 中以一对多关系将父对象添加到子对象。现在我想知道在使用新创建的子级创建或更新父级时如何同时将它们保存在服务器上。
服务器会期望这样的事情:
parent {
prop1: 'val1',
prop2: 'val2',
child: {
prop1: val1
prop2: val2
}
}
但 ember 的有效负载如下所示:
parent {
prop1: 'val1',
prop2: 'val2',
child:null
}
当将已有的子项附加到父项时,更新也是如此。然后有效负载看起来像这样:
parent {
prop1: 'val1',
prop2: 'val2',
child:2
}
所以它不是随有效负载传输的子对象,而只是它的 id(如果存在的话)(否则为 null))。是否可以像服务器期望的那样发送嵌套对象,或者我是否必须使用两个 ajax-post/put-requests 分别保存两个模型?
最佳答案
我不确定为什么你的服务器期望这样的事情,但你可以这样实现。
首先在您放置的父模型上
child: DS.attr("") //this will give you ability to send any type in your case object to property child.
然后在哪里创建子项
this.store.createRecord('parent',{
child: this.store.createRecord('child',{name: "John"})
});
或者如果你有类似的东西
let parent = this.store.findRecord("parent", 1);
let child = this.store.createRecord('child',{name: "John"});
parent.set("child", child);
我个人会避免它,但你可以在 js 中做任何你想做的事情。
关于javascript - 如何在ember js中保存嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43538901/