Ember数据关系未解决

时间:2017-03-16 07:30:02

标签: ember.js ember-data

我还在学习ember.js,并且遇到了一个包含数据并没有解析模型中查找关系的ember数据的障碍。我有一个模特'网站'这基本上是每个其他模型的查找表,以根据位置区分数据。

此时,我做错了什么或错过了一个关键概念 - 可能两者......(或者也许是凌晨!)

网站模型(即查找表)

import DS from 'ember-data';

export default DS.Model.extend({
    code: DS.attr(),
    name: DS.attr(),
});

网站模型与我的所有其他模型之间存在hasMany关系(完成时大约为12)

关联模式

import DS from 'ember-data';
import { belongsTo } from 'ember-data/relationships';

export default DS.Model.extend({
    site: belongsTo('site'),
    last: DS.attr(),
    first: DS.attr(),
    active: DS.attr('boolean'),

fullName: Ember.computed('first', 'last', function() {
  return `${this.get('first')} ${this.get('last')}`;
  }),
});

'关联模式'也将与' site'一起查找。在其他一些模型中。

我通过JSON API规范提供数据,但我不包括关系数据,因为根据我的理解,它应该使用网站ID属性来删除网站数据。

{
    "links": {
        "self": "/maint/associates"
    },
    "data": [
        {
            "type": "associate",
            "id": "1",
            "attributes": {
                "site": "6",
                "last": "Yoder",
                "first": "Steven",
                "active": "1"
            },
            "links": {
                "self": "/associates/1"
            }
        }
    ]
}

在我的模板文件中,我引用了associate.site,这给了我一个错误。

  

<(未知mixin):ember431>

如果我使用associate.code或.name来匹配网站模型,则模板中不会显示任何内容。来自'网站的代码' table是我真正希望在模板中显示的数据。

所以显而易见的问题是:

  1. 我错了,Ember Data应该解决这个问题,还是我需要解决的问题 在我的API响应中包含关系?

  2. 我意识到我属于'员工'仅限模型参考 网站,而我想要site.code,所以我如何建立这种关系 知道或访问我的'关联的字段模型

  3. 我没有在'网站中包含hasMany关系。因为 会有很多。我需要做一个反向关系吗? 其他型号?我见过的例子并没有显示出hasMany 关系设置。

  4. 当我在ember检查器中查看模型时,站点字段不是 包含在模型中。即使我没有得到正确的数据 它还应该出现吗?

  5. 到目前为止,我喜欢使用ember,只需要理解并克服这个障碍

    更新:我的后端JSON库只会根据当前规范

    生成关系链接
    "related": "/streams/1/site"
    

    但是ember数据会调用

    "相关":" / sites / 1"

    解决关系

    所以@Adam Cooper的回答是正确的,如果您回答时生成链接,或者只能根据当前规范生成链接。

1 个答案:

答案 0 :(得分:1)

如果你正在使用默认的JSONAPIAdapter,你希望你的回复看起来像这样:

{
  "links": {
    "self": "/maint/associates"
  },
  "data": [{
    "type": "associate",
    "id": "1",
    "attributes": {
      "last": "Yoder",
      "first": "Steven",
      "active": "1"
    },
    relationships: {                  
      "site": {
        "links": {  
          related: "/sites/6"
        }
      } 
    }
  }]
}

这将允许Ember Data通过其关系查找网站。现在,Ember正在尝试访问Ember Data无法填充的网站模型,因此您将获得错误。另外,你可以做一些返回活动的实际布尔值。

相关问题