为什么在hasMany创建成功后,我需要手动推送Object



我有一个hasMany/belongsTo关系

App.Appointment = DS.Model.extend({
employee: belongsTo('employee', { async: true})
});
App.Employee = DS.Model.extend({
appointments: hasMany('appointment', { async: true})
});

我有一个简单的表格,可以创建预约

var appointment = {
employee: employee (another ember-data model)
}
this.store.createRecord('appointment', appointment).save().then(function(apt) {
self.get('target').transitionTo('day.index');
}

如果我执行上述操作,我的"employees"数组永远不会正确显示相反的结果(即,当我稍后执行employee.get("appointments")之类的操作时,它不会反映新的约会;

我已经能够通过下面的来"解决"这个问题

this.store.createRecord('appointment', appointment).save().then(function(apt) {
employee.get('appointments').pushObject(apt);
employee.save();
self.get('target').transitionTo('day.index');
}

我不喜欢这个有两个原因

  1. 我觉得如果我的成员数据连接正确,它应该只是"知道"我已经为相关员工添加了一个新的约会(作为我看到它穿过电线)

  2. 这会强制在我的hasMany上进行"查找"(因此它会触发一个请求要求员工使用apts——经常会混淆"如何许多"我想为给定的上下文显示的apt)

我的关系设置正确吗?或者这是ember数据1.0测试版4/5中的一个错误?

我目前正在使用ember.js 1.3.1 的ember数据1.0测试版4

值得一提的是,以下是我目前用于对"items"进行递归保存的内容。他们有孩子,并且拥有与他们相关联的权限。同样值得注意的是,这些项是递归的(因此,这些项可以有子项,也就是可以有子级的项…等等)。这将处理某些项已保存或不包括所有父项重新关联的情况。它对我有效。这可能会帮助你(或者它可能只是让你完全困惑,我希望不会。)

如果你能从中得到一些有用的东西,那就太棒了:)

同样值得注意的是,我不会对我的错误捕获做任何事情。显然,这并不理想!

saveAll: function() {
var saveExistingObjects, self;
saveExistingObjects = function(item) {
var promise;
promise = new Ember.RSVP.Promise(function(resolve, reject) {
return item.get('childItems').then(function(childItems) {
var childPromises;
childPromises = childItems.map(function(childItem) {
return saveExistingObjects(childItem);
});
return Ember.RSVP.all(childPromises).then(function(arrayOfSavedChildren) {
var itemPermissions, itemWasNew;
itemWasNew = item.get('isNew');
itemPermissions = item.get('itemPermissions');
return item.save().then(function(savedItem) {
if (itemWasNew) {
arrayOfSavedChildren.forEach(function(childItem) {
childItem.set('parentItem', savedItem);
return childItem.save();
});
itemPermissions.forEach(function(itemPermission) {
itemPermission.set('item', savedItem);
return itemPermission.save();
});
}
savedItem.set('childItems', []);
Ember.RSVP.Promise.cast(savedItem.get('childItems')).then(function(cb) {
return cb.addObjects(arrayOfSavedChildren);
});
return resolve(savedItem);
})["catch"](function(error) {
console.log("Didn't save!");
return reject(error);
});
})["catch"](function(error) {
console.log("Didn't finish saveExistingObjects and returning childPromises");
console.log(error);
return reject(error);
});
})["catch"](function(error) {
console.log("Didn't get childItems");
console.log(error);
return reject(error);
});
});
return promise;
};
self = this;
return saveExistingObjects(self);
}

最新更新