我正在使用模型“鸡尾酒”、“会员”和“成分”创建一个鸡尾酒应用程序。鸡尾酒和配料模型非常容易解释,会员模型适用于将鸡尾酒与配料联系起来的对象。
App.Cocktail = DS.Model.extend({
name: DS.attr('string'),
description: DS.attr('string'),
created_by: DS.attr('number'),
start_date: DS.attr('string'),
end_date: DS.attr('string'),
// link cocktail to memberships
membership: DS.hasMany('membership',{ async: true })
});
App.Membership = DS.Model.extend({
amount: DS.attr('string'),
// link membership to ingredient and cocktail
ingredient: DS.belongsTo('ingredient'),
cocktail: DS.belongsTo('cocktail')
});
App.Ingredient = DS.Model.extend({
name: DS.attr('string'),
description: DS.attr('string'),
start_date: DS.attr('string'),
end_date: DS.attr('string')
});
我遇到的问题是,当我使用 ember-data 创建鸡尾酒,然后它的成员资格成分和 REST 调用的鸡尾酒 ID 是字符串而不是整数时,请求正文如下所示:
{membership:{amount:"2 litres",ingredient:"12",cocktail:"116"}}
当我想要什么时:
{membership:{amount:"2 litres",ingredient:12,cocktail:116}}
这是我执行保存的代码,我对 Promise 的想法很陌生,所以不确定这是否以最可取的方式构建。
... code
actions: {
// fired when user presses save
submit: function() {
// some validation
var cocktailPromise = this._saveCocktail();
this._saveIngredientMemberships(cocktailPromise);
}
}
... more code
_saveCocktail: function() {
console.log('saving cocktail');
var cocktail = this.store.createRecord('cocktail', {
name: this.get('cocktailName'),
description: this.get('cocktailDescription'),
start_date: "now"
});
return cocktail.save();
},
_saveIngredientMemberships: function(cocktailPromise) {
console.log('saving cocktail ingredients');
// get the ingredients and amounts (memberships) the
// user entered and the store and set them as var here
// so they stay in scope.
var memberships = this.get('memberships');
var store = this.store;
// once cocktail is created
cocktailPromise.then(function(cocktail) {
console.log('cocktail ready, saving ingredients');
var membershipRecords = [];
for( var i = 0 ; i < memberships.length ; i++ ) {
membershipRecords[i] = store.createRecord('membership', {
cocktail: cocktail,
ingredient: memberships[i].get('ingredient'),
amount: memberships[i].get('amount')
});
membershipRecords[i].save();
}
}, function() {
console.log('something went wrong saving the cocktail!');
})
},