【问题标题】:Accessing Ember data has-many relationship on template访问 Ember 数据在模板上有很多关系
【发布时间】:2017-07-19 18:45:55
【问题描述】:

我有一个 Rails 后端,按照 JSON API 标准 (jsonapi-resources gem) 提供数据。我有两个模型:联系人和电话号码。

class Contact < ApplicationRecord
  has_many :phone_numbers
end

class PhoneNumber < ApplicationRecord
  belongs_to :contact
end

这是 API 端点的 JSON 响应。

{
    "data": [
        {
            "id": "6",
            "type": "phone-numbers",
            "links": {
                "self": "http://localhost:3000/phone-numbers/6"
            },
            "attributes": {
                "name": "byeworld",
                "phone-number": "9212098"
            },
            "relationships": {
                "contact": {
                    "links": {
                        "self": "http://localhost:3000/phone-numbers/6/relationships/contact",
                        "related": "http://localhost:3000/phone-numbers/6/contact"
                    }
                }
            }
        }
    ]
}

这些是我的 Ember 模型:

联系方式:

import DS from 'ember-data';

export default DS.Model.extend({
  nameFirst: DS.attr('string'),
  nameLast: DS.attr('string'),
  email: DS.attr('string'),
  twitter: DS.attr('string'),
  phoneNumbers: DS.hasMany('phone-number', {async: true, inverse: 'contact'})
});

电话号码:

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  phoneNumber: DS.attr('string'),
  contact: DS.belongsTo('contact', {async: true, inverse: 'phoneNumbers'})
});

这是我的路由处理程序:

import Ember from 'ember';

export default Ember.Route.extend({
  model(params) {
    return this.store.findRecord('contact', params.contact_id, {include: "phone-numbers"});
  },
  (...)
});

我无法通过以下方式访问模板上联系人的电话号码:

{{#each model.phoneNumbers as |phone|}}
  {{phone.name}}
{{/each}}

此外,电话号码的数据存在于 ember 控制台中。我错过了什么?

【问题讨论】:

  • 你的 ember-data 版本是多少?
  • "ember-data": "~2.14.3"

标签: ruby-on-rails json ember.js


【解决方案1】:

ember-data 版本 2.14.3 中存在未解决的已知问题。所以请将您的 ember-data 版本降级到 2.13.2 。这可能会解决您的问题。

参考这个 ember-data 开放问题 - https://github.com/emberjs/data/issues/4942

【讨论】:

    【解决方案2】:

    model.PhoneNumbers => model.phoneNumbers

    如果这不仅仅是这个错字,请尝试从 JSON API 适配器/序列化器扩展您的模型序列化器/适配器(或者如果您的所有模型都使用它,则在您的应用程序序列化器/适配器上进行):

    import DS from 'ember-data'; export default DS.JSONAPIAdapter.extend({});

    和:

    import JSONAPISerializer from 'ember-data/serializers/json-api'; export default JSONAPISerializer.extend({});

    【讨论】:

    • 感谢您的建议,抱歉打错了。它没有帮助。我不知道这是否有帮助,但我在控制台中收到 You modified "model.phoneNumbers" twice on &lt;front-end@model:contact::ember348:3&gt; in a single render.Cannot read property 'getAttribute' of undefined 错误。
    • 我现在在 app/adapters 中有一个 application.js,其中包含您第一个建议中的代码。遗憾的是没有任何改善。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    相关资源
    最近更新 更多