gpt4 book ai didi

ember.js - createRecord 与belongsTo 关联

转载 作者:行者123 更新时间:2023-12-02 08:00:39 25 4
gpt4 key购买 nike

我尝试存储具有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"
}}

最佳答案

这是旧版本的 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'

关于ember.js - createRecord 与belongsTo 关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20499008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com