我正在尝试使用belongsTo关联存储记录,但关联的ID始终为空:
客户模式
Docket.Customer = DS.Model.extend({
name: DS.attr('string'),
initial: DS.attr('string'),
description: DS.attr('string'),
number: DS.attr('string'),
archived: DS.attr('boolean'),
projects: DS.hasMany('project',{ async: true })
});
项目模型
Docket.Project = DS.Model.extend({
name: DS.attr('string'),
description: DS.attr('string'),
number: DS.attr('string'),
archived: DS.attr('boolean'),
customer: DS.belongsTo('customer')
});
在ProjectsController中保存操作
var _this = this;
// create new record
var project = this.store.createRecord('project', this.getProperties('name','number', 'description', 'archived'));
// add customer with id 22 to project
this.store.find('customer', 22).then(function(customer) {
project.set('customer', customer);
});
// save if validation passes, otherwise show errors
project.save().then(function(){
_this.resetAndCloseForm(form);
}, function(response){
_this.set('errors',response.errors);
});
发送到服务器的json始终如下:
archived: false
customer_id: null
description: null
name: "foobar"
number: null
我想在选择框中选择项目的客户。是否有任何智能方法可以将所选客户作为记录,还是必须将其加载到ID上?
{{view Ember.Select
viewName="select"
contentBinding="customers"
optionLabelPath="content.name"
optionValuePath="content.id"
prompt="Pick a customer:"
selectionBinding="selectedCustomer"
}}
答案 0 :(得分:2)
这是ember数据的旧版本,还是您有自定义序列化程序,因为它应该在没有_id
的情况下发送它。尝试升级或显示序列化程序。
在解决问题之前,你要保存。
// add customer with id 22 to project
this.store.find('customer', 22).then(function(customer) {
project.set('customer', customer);
// save if validation passes, otherwise show errors
project.save().then(function(){
_this.resetAndCloseForm(form);
}, function(response){
_this.set('errors',response.errors);
});
});
看起来selectedCustomer
有记录。
// create new record
var project = this.store.createRecord('project', this.getProperties('name','number', 'description', 'archived'));
project.set('customer', this.get('selectedCustomer'));
// save if validation passes, otherwise show errors
project.save().then(function(){
_this.resetAndCloseForm(form);
}, function(response){
_this.set('errors',response.errors);
});
您也可以设置optionValuePath='content'