我正在构建一个适配器来包装Keen.io API,到目前为止,我已经能够成功加载项目资源,但是返回的对象如下所示:
{
partners_url: "/3.0/projects/<ID>/partners",
name: "Project Name",
url: "/3.0/projects/<ID>",
saved_queries: [ ],
events_url: "/3.0/projects/<ID>/events",
id: "<ID>",
organization_id: "<ORG ID>",
queries_url: "/3.0/projects/<ID>/queries",
api_key: "<API KEY>",
events: [
{
url: "/3.0/projects/<ID>/events/user_signup",
name: "user_signup"
},
{
url: "/3.0/projects/<ID>/events/user_converted",
name: "user_converted"
},
{
url: "/3.0/projects/<ID>/events/user_created_project",
name: "user_created_project"
}
]
}
排除很多错误,Ember使用name
映射id
和RESTSerializer
属性没有问题,但如果我为events
添加Project
关系1}}模型爆炸:
Error while loading route: TypeError: Cannot set property 'store' of undefined
at Ember.Object.extend.modelFor (http://localhost:3000/assets/ember-data.js?body=1:9813:23)
at Ember.Object.extend.recordForId (http://localhost:3000/assets/ember-data.js?body=1:9266:21)
at deserializeRecordId (http://localhost:3000/assets/ember-data.js?body=1:10197:27)
at deserializeRecordIds (http://localhost:3000/assets/ember-data.js?body=1:10211:9)
at http://localhost:3000/assets/ember-data.js?body=1:10177:11
at http://localhost:3000/assets/ember-data.js?body=1:8518:20
at http://localhost:3000/assets/ember.js?body=1:3404:16
at Object.OrderedSet.forEach (http://localhost:3000/assets/ember.js?body=1:3247:10)
at Object.Map.forEach (http://localhost:3000/assets/ember.js?body=1:3402:10)
at Function.Model.reopenClass.eachRelationship (http://localhost:3000/assets/ember-data.js?body=1:8517:42)
根据我的调查,这似乎是因为它无法找到将Event
映射回Project
的反向关系,因为没有父ID。
是否可以在Ember Data中创建关系以支持此功能?或者是否可以修改序列化程序以在加载前为每个事件追加projectId
?
我使用的是Ember 1.5.0-beta.4和Ember Data 1.0.0-beta.7 + canary.f482da04。
答案 0 :(得分:1)
假设您的Project
模型设置如下:
App.Project = DS.Model.extend({
events: DS.hasMany('event');
});
您需要确保API中的JSON具有Ember-Data所期望的特定形状。
{
"project": {
"id": 1,
"events": ["1", "2"],
},
"events": [{
"id": "1",
"name": "foo"
}, {
"id": "2",
"name": "bar"
}]
}
但是,您可以在模型的序列化程序中实现extractArray
,将JSON从服务器转换为类似上述示例的内容。
Ember docs中有一个工作示例和解释。