Ember Data 1.0.0:belongsTo关系的预期格式是什么

cyc*_*arc 4 ember.js ember-data

我有以下型号:

App.Publication = DS.Model.extend({
  title: DS.attr('string'),
  bodytext: DS.attr('string'),
  author: DS.belongsTo('author')
});

App.Author = DS.Model.extend({
  name: DS.attr('string')
});
Run Code Online (Sandbox Code Playgroud)

以下是json数据:

{
  "publications": [
  {
    id: '1',
    title: 'first title',
    bodytext: 'first body',
    author_id: 100
  },
  {
    id: '2',
    title: 'second title',
    bodytext: 'second post',
    author_id: 200
  }
];
}
Run Code Online (Sandbox Code Playgroud)

在Ember Data RC12中,这有效(您可以在json中指定author_id或作者,并且出版物将始终链接正确的作者).

在Ember Data 1.0.0中,这不再有效; 作者总是空的.

在一些文档中,我发现 - 因为我在json数据中使用"author_id"(而不仅仅是作者) - 我需要在模型中指定键; 从而:

 author: DS.belongsTo('author', { key: 'author_id' })
Run Code Online (Sandbox Code Playgroud)

然而,这不起作用; 该出版物中的作者仍为空.

我现在看到的唯一解决方案是实现自定义序列化程序并将author_id覆盖为author(通过normailzeId); 我无法改变我的后端数据结构...因此:

App.MySerializer = DS.RESTSerializer.extend({
  //Custom serializer used for all models
  normalizeId: function (hash) {
    hash.author = hash.author_id;
    delete hash.author_id;
    return hash;
  }
});
Run Code Online (Sandbox Code Playgroud)

以上是正确的方法吗?

小智 7

默认情况下,Ember Data 1.0不再执行任何有效负载标准化.该key用于配置DS.belongsTo已被删除,以及所以你必须实现自定义序列化.

normalizeId是一个内部序列化函数,用于将主键转换为始终可用id.你不应该覆盖它.

相反,您可以覆盖keyForRelationship为此目的提供的方法.

您可以使用以下内容:

App.ApplicationSerializer = DS.RESTSerializer.extend({
  keyForRelationship: function(rel, kind) {
    if (kind === 'belongsTo') {
      var underscored = rel.underscore();
      return underscored + "_id";
    } else {
      var singular = rel.singularize();
      var underscored = singular.underscore();
      return underscored + "_ids";
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

注意:我还重命名了序列化程序,App.ApplicationSerializer以便它可以用作应用程序的默认序列化程序.

最后,如果您还没有找到它,请在此处查看转换说明:https://github.com/emberjs/data/blob/master/TRANSITION.md

如果您在最初的1.0.0.beta.1版本之后不久阅读了转换文档,我建议您再次查看,因为已经添加了许多内容,特别是有关序列化的内容.