2014-11-01 51 views
3

大多数人在加载嵌入式Ember模型时遇到问题,但我遇到了一个相反的问题。加载空/可选嵌入式与Ember Data有很多关系

当我尝试解析包含embedded关系的记录时,Ember抛出错误,其中hasMany关系的内容为空数组。

你如何使一个嵌入式Ember数据hasMany关系可选或可为空?

我有一个模型..

App.Beat = DS.Model.extend({ 

    notes: DS.hasMany('note', { 
    embedded: 'always', 
    defaultValue: [] 
    }), 

    ... 
}) 

该模型是在一个Bar模型,它是在Track模型的关联的关联。这些在这里并不重要。

这些嵌入式hasMany关系得到序列化有以下串行..

// http://bl.ocks.org/slindberg/6817234 
App.ApplicationSerializer = DS.RESTSerializer.extend({ 

    // Extract embedded relations from the payload and load them into the store 
    normalizeRelationships: function(type, hash) { 
    var store = this.store; 

    this._super(type, hash); 

    type.eachRelationship(function(attr, relationship) { 
     var relatedTypeKey = relationship.type.typeKey; 

     if (relationship.options.embedded) { 
     if (relationship.kind === 'hasMany') { 
      hash[attr] = hash[attr].map(function(embeddedHash) { 
      // Normalize the record with the correct serializer for the type 
      var normalized = store.serializerFor(relatedTypeKey).normalize(relationship.type, embeddedHash, attr); 

      // If the record has no id, give it a GUID so relationship management works 
      if (!normalized.id) { 
       normalized.id = Ember.generateGuid(null, relatedTypeKey); 
      } 

      // Push the record into the store 
      store.push(relatedTypeKey, normalized); 

      // Return just the id, and the relation manager will take care of the rest 
      return normalized.id; 
      }); 
     } 
     } 
    }); 
    } 
}); 

成功反序列化,并在应用商店装载记录,地方上的Trackbars属性后得到访问。如果Bar具有的beats那些beats的一个没有任何notes(因为是休息击败在没有票据获得出场),那么下面的错误被抛出:

“你抬起头来‘酒吧’关系“,但某些相关记录未加载,要么确保它们全部与父记录一起加载,要么指定关系为异步(DS.hasMany({async:true}))”

该错误来自ember-data.js中的以下断言:hasRelationship:

Ember.assert("...", Ember.A(records).everyProperty('isEmpty', false)); 

其中recordsbars的数组,其包含可选地包含notes的节拍。

那么,如何让我的embeddedhasMany关系可选所以它接受的记录空数组?

回答

0

原来我们认为这是对我的bar模式isEmpty与当时正在财产发生冲突在Ember声明中进行了测试。重命名这个属性使所有的工作。

1

我建议在最近的Ember Data beta(10或11)中使用EmbeddedRecordsMixin,然后看看你是否仍然有嵌入记录的问题。

您的应用程序序列化:

App.ApplicationSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin,{ 
    // probably nothing required here yet 
}); 

,然后在拍的模型序列:

App.BeatSerializer = App.ApplicationSerializer.extend({ 
    attrs: { 
    notes: { embedded: 'always' } 
    } 
}); 
+0

从1.0.0.7升级到1.0.0.11,并重构为EmbeddedRecordsMixin,但问题依然存在。 – Tails 2014-11-10 11:17:25