【发布时间】:2014-09-05 03:08:13
【问题描述】:
我正在为 DreamFactory 服务平台编写一个 ember-data 适配器,遇到了一个我认为与我的适配器有关的问题。
更新现有记录时,model.save() 产生的承诺总是被拒绝,错误为
Assertion Failed: An adapter cannot assign a new id to a record that already has an id. <App.Event311:1> had id: 1 and you tried to update it with null. This likely happened because your server returned data in response to a find or update that had a different id than the one you sent
问题是 - 对 REST API 的请求和从 REST API 返回的响应具有相同的 ID!
请求(PUT)
{
"record": {
"id": "1",
"title": "Sample Event",
"date": "7/20/2013",
"type": "success",
"desc": "My first sample event."
}
}
响应
{
"record": [
{
"id": 1,
"title": "Sample Event",
"date": "7/20/2013",
"type": "success",
"desc": "My first sample event."
}
]
}
真正奇怪的是记录仍然在存储中正确更新和在数据库中!
我在http://emberjs.jsbin.com/mosek/1/edit 有一个可以工作的 JSBin,它说明了这个问题。我的自定义适配器位于 GitHub 上的 https://github.com/ultimatemonty/ember-data-dreamfactory-adapter。 JSBin 和我的应用程序正在使用 Ember 1.7.0 和 ED 1.0.0-beta.9
编辑
JSBin 附加到我的 DreamFactory 个人托管实例 - 除了允许从 JSBin 访问之外,我没有对它做任何事情,但请保持温和 :)
* 编辑 #2 *
updateRecord 代码可在 GitHub 上的 https://github.com/ultimatemonty/ember-data-dreamfactory-adapter/blob/master/lib/ember-data-dreamfactory-adapter.js#L106 访问,但这里是完整的参考方法:
updateRecord: function(store, type, record) {
var data = {};
var serializer = store.serializerFor(type.typeKey);
serializer.serializeIntoHash(data, type, record);
var adapter = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
// hack to make DSP send back the full object
adapter.ajax(adapter.buildURL(type.typeKey) + '?fields=*', "PUT", { data: data }).then(function(json){
// if the request is a success we'll return the same data we passed in
resolve(json);
}, function(reason){
reject(reason.responseJSON);
});
});
}
【问题讨论】:
-
错误信息说您不能使用 id 发帖。为什么不删除id? Ember Data 期望服务器分配它。
-
@torazaburo 这是对现有模型的更新,所以我需要 id 来执行更新。
-
在 ajax 请求之后尝试从您的商店中卸载记录。
-
更新是 PUT,而不是 POST。
标签: rest ember.js ember-data