我正在根据表单数据和另一个 promise (用于相关记录)创建一条记录。
这是我所关注的基本 JSON
//appointment
{
"id": 6,
"details": "test",
"customer": 1
}
//customer
{
"id": 1,
"name": "Sle eep",
"appointments": [6]
}
我的 ember-data 模型看起来像这样
App.Appointment = DS.Model.extend({
details: attr('string'),
customer: belongsTo('customer', { async: true})
});
App.Customer = DS.Model.extend({
name: attr('string'),
appointments: hasMany()
});
当我创建约会时,它目前看起来像这样
this.store.find('customer', 1).then(function(customer) {
var appointment = {
details: 'foo',
customer: customer.get('id')
}
this.store.createRecord('appointment', appointment).save();
});
上面的问题是,当表单数据是一个 promise 时,我的序列化器表现不佳。这是我应该如何创建记录吗?如果不是,这个创建应该是什么样子?
提前谢谢
更新
经过一番查看后,belongsTo 上的 async: true 似乎可能是问题所在。在“createRecord”之前我可以看到以下内容
Object {details: "asd", customer: 1}
但是当我跳到 ember-data 的“createRecord”方法(在 RESTAdapter 中)时,我注意到现在客户再次被表示为 promise (不是我在调用该方法之前看到的整数值或字符串值)
最佳答案
为什么不在创建记录并发送之前等待查找结果得到解决?
var self = this,
promise = this.store.find('customer', 1); //just to show it's a promise
promise.then(function(customer){
var appointment = {
details: 'foo',
customer: customer
}
self.store.createRecord('appointment', appointment).save();
},{
alert("uh oh end of the world, couldn't find customer");
});
异步没有很好的记录,并且似乎有一些随意的副作用(它仍处于测试阶段,所以我还没有做出重大判断)。话虽如此,您的约会 hasMany 尚未定义,这里有一个 Playground 。
关于ember.js - 如何在ember-data 1.0中提交带有相关模型数据的表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20341348/