1

我正在构建一个适配器来包装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"
    }
  ]
}

name排除很多杂乱无章的东西,Ember 使用 映射和id属性没有问题RESTSerializer,但是如果我events向我的模型添加一个关系,Project它会爆炸:

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) 

根据我的调查,这似乎是因为它找不到将 a 映射Event回 a的反比关系,Project因为没有父 ID。

是否可以在 Ember Data 中创建关系来支持这一点?或者是否可以projectId在加载之前修改序列化程序以将 a 添加到每个事件?

我正在使用 Ember 1.5.0-beta.4 和 Ember Data 1.0.0-beta.7+canary.f482da04。

4

1 回答 1

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 文档中有一个工作示例和解释。

于 2014-03-16T21:00:16.027 回答