ember-使用其他查找结果获取的模型查找数据

ember-data find using a model fetched using other find's result

我正在使用这个设置:

Ember      : 1.10.0
Ember Data : 1.0.0-beta.16
jQuery     : 1.11.2
ember-localstorage-adapter: 0.5.2

我设法使用 ember-cli 在我的数据存储区 (Localstorage) 中存储了一些数据

现在,我想检索数据。我的模型中有 3 个 类:

mtg-item.js
  name: DS.attr('string'),
  material: DS.attr('string'),
  description: DS.attr('string')

mtg-point.js
  long: DS.attr('string'),
  lat: DS.attr('string')

mtg-item-at-point.js
  item: DS.belongsTo('mtgItem', {inverse: null}),
  position: DS.belongsTo('mtgPoint', {inverse: null})

这是本地存储中的数据:

mantrailling-item: "{"mtgItem":{"records":{"an0jf":{"id":"an0jf","name":"chaussette","material":"tissu","description":"carré de tissus"}}}}"
mantrailling-item-at-point: "{"mtgItemAtPoint":{"records":{"r7v07":{"id":"r7v07","item":"an0jf","position":"qqnpa"}}}}"
mantrailling-point: "{"mtgPoint":{"records":{"qqnpa":{"id":"qqnpa","long":"0","lat":"0"}}}}"mantrailling-style: "{"mtgStyle":{"records":{"rggrm":{"id":"rggrm","name":"default","path":null}}}}"__proto__: Storage

当我尝试检索数据时,检索 mtgItem 和 mtgPoint 没有问题。 问题是在尝试检索 mtgItemAtPoint 时。 我收到断言错误:

Error: Assertion Failed: You cannot add a 'undefined' record to the 'mtgItemAtPoint.item'. You can only add a 'mtgItem' record to this relationship.

调试时,我观察到它发生在尝试设置 mtgItem 时。 我在 belongs-to.js 文件第 70 行缩小了搜索范围。

  var type = this.relationshipMeta.type;
  Ember.assert("You cannot add a '" + newRecord.constructor.typeKey + "' record to the '" + this.record.constructor.typeKey + "." + this.key +"'. " + "You can only add a '" + type.typeKey + "' record to this relationship.", (function () {
    if (type.__isMixin) {
      return type.__mixin.detect(newRecord);
    }
    if (Ember.MODEL_FACTORY_INJECTIONS) {
      type = type.superclass;
    }
    return newRecord instanceof type;
  })());

断言试图检查 newRecord 是否扩展了超类型 DS.Model。

当我在调试中检索值时,这是我得到的类型和 newRecord:

newRecord.type.__super__.constructor
(subclass of DS.Model)

type
(subclass of DS.Model)

所以我不明白为什么会出现以下情况:

return newRecord instanceof type

returns假的?

郑重声明,我是这样调用查找的:

var mtgItem = store.find('mtgItem', {name: "chaussette", material: "tissu"});
mtgItem.then(function(mtgItem) {
    var mtgPoint = store.find('mtgPoint', {long: "0", lat: "0"});
    mtgPoint.then(function(mtgPoint) {
        var mtgItemAtPoint = store.find('mtgItemAtPoint', {item: mtgItem, position: mtgPoint});
    });
});

经过几个小时的睡眠我想通了(像往常一样...)

问题是 store.find returns 是 Ember.Enumerable 而不是记录。因此,您需要遍历结果以获得正确的 DS.Model 对象。在我的例子中,我只需要 一个 记录,所以我使用第一个对象。

修复如下:

var mtgItems = store.find('mtgItem', {name: "chaussette", material: "tissu"});
mtgItems.then(function(mtgItems) {
    var mtgItem = mtgItems.get("firstObject");
    var mtgPoints = store.find('mtgPoint', {long: "0", lat: "0"});
    mtgPoints.then(function(mtgPoints) {
        var mtgPoint = mtgPoints.get("firstObject");
        var mtgItemAtPoints = store.find('mtgItemAtPoint', {item: mtgItem, position: mtgPoint});
    });
});