大多数人在加载嵌入式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;
});
}
}
});
}
});
成功反序列化,并在应用商店装载记录,地方上的Track
的bars
属性后得到访问。如果Bar
具有的beats
那些beats
的一个没有任何notes
(因为是休息击败在没有票据获得出场),那么下面的错误被抛出:
“你抬起头来‘酒吧’关系“,但某些相关记录未加载,要么确保它们全部与父记录一起加载,要么指定关系为异步(DS.hasMany({async:true}))”
该错误来自ember-data.js中的以下断言:hasRelationship:
Ember.assert("...", Ember.A(records).everyProperty('isEmpty', false));
其中records
是bars
的数组,其包含可选地包含notes
的节拍。
那么,如何让我的embedded
hasMany
关系可选所以它接受的记录空数组?
从1.0.0.7升级到1.0.0.11,并重构为EmbeddedRecordsMixin,但问题依然存在。 – Tails 2014-11-10 11:17:25