对于具有替代主键

时间:2016-08-19 12:15:22

标签: javascript json ember.js

我的Ember.js应用程序存在问题。它使用JSONAPI{Adapter,Serializer}和以下模型:

models/node.js

App.Node = DS.Model.extend(
{
  // (node 'name' field used as primary key for serialization)

  info: DS.attr('string'),
  children: DS.hasMany('node', { inverse: null })
}

表示命名节点树。

JSONAPIAdapter( adapters/application.js )实现函数queryRecord()query()findRecord()findAll()来翻译Ember。来自服务器的js查询。一切正常。

JSONAPISerializer实现函数normalizeResponse()以将服务器响应JSON数据转换为json:api格式。在序列化程序中,主键被定义为节点的“名称”字段:

serializers/application.js

App.ApplicationSerializer = DS.JSONAPISerializer.extend(
{
  primaryKey: 'name',

  normalizeResponse(store, primaryModelClass, payload, id, requestType)
  {
    // ...
  }
});

序列化程序生成的json:api数据示例为:

{
  "data": [
    {
      "type": "node",
      "attributes": {
        "info": "Root node"
      },
      "relationships": {
        "children": {
          "data": [
            {
              "type": "node",
              "name": "Root/SubNode1"
            }
          ]
        }
      },
      "name": "Root"
    }
  ],
  "included": [
    {
      "type": "node",
      "attributes": {
        "info": "Subnode 1"
      },
      "relationships": {
        "children": {
          "data": [
          ]
        }
      },
      "name": "Root/SubNode1"
    }
  ]
}

我使用Ember.js版本2.7.0和Ember检查员。

应用程序运行后,数据加载到模型中,我可以看到Ember检查器中的数据在模型中可见。但是,在“数据”视图中调查模型数据(并选择项目)时,我发现Ember正在使用adapter:findRecord()调用id = null,从而导致错误查询。不知怎的,似乎模型数据不正确。

当我删除JSONAPISerializer中的主键定义并将name字段中的节点的id字段复制为Ember默认主键时,一切正常。我的主键定义缺少什么? Ember指南仅说明有关序列化程序中primaryKey的信息(https://guides.emberjs.com/v2.7.0/models/customizing-serializers/#toc_ids)。

非常感谢提前!

1 个答案:

答案 0 :(得分:0)

您需要定义name字段以获得保存ID的位置。

App.Node = DS.Model.extend(
{
  // (node 'name' field used as primary key for serialization)
  name: DS.attr('string'),
  info: DS.attr('string'),
  children: DS.hasMany('node', { inverse: null })
}