我正在尝试创建一个具有hasMany / belongsTo关联的记录。记录已创建,但无法保存...
故事模型:
export default DS.Model.extend({
title: DS.attr('string'),
description: DS.attr('string'),
tasks: DS.hasMany('task', { async: true })
});
任务模型:
export default DS.Model.extend({
title: DS.attr('string'),
story: DS.belongsTo('story', { async: true })
});
组件对象:
actions: {
createNewTask(){
var taskTitle = this.get('newTaskTitle');
var tasks = this.get('story.tasks');
var story = this.get('story');
this.set('newTaskTitle', '');
this.sendAction('action', taskTitle, tasks, story);
this.send('toggleModal');
}
在上面,story = model和this.get('story.tasks')总是返回一个空数组。
路线对象:
export default Ember.Route.extend({
model: function(params){
return this.store.findRecord('story', params.id);
},
actions: {
createNewTask(newTaskTitle, tasks, story){
var newTask = this.store.createRecord('task', {
title: newTaskTitle
});
newTask.save().then(function(task){
//I think the issue is somewhere in here
tasks.addObject(task);
story.save();
});
}
}
基本上,创建的任务没有与它相关的故事一起保存......任何帮助都会很棒。谢谢!
修改的 这是我本地存储中存储的json
{
"story":{
"records":{
"3jf2h":{
"id":"3jf2h",
"title":"Story1",
"description":"Story1",
"tasks":[
"6i03h"
]
}
}
},
"task":{
"records":{
"6i03h":{
"id":"6i03h",
"title":"T1",
"description":"T1",
"story":null
}
}
}
}
答案 0 :(得分:1)
在解决问题后,我找到了解决方案,但我不确定它是否是最佳解决方案...
在我的故事路线中:
actions: {
createNewTask(newTaskTitle, newTaskDesc, tasks, taskType, story){
var newTask = this.store.createRecord('task', {
title: newTaskTitle,
description: newTaskDesc,
status: 'Not Started',
type: taskType
});
newTask.save().then(function(task){
tasks.addObject(task);
story.save().then(function(){
task.set('story', story);
task.save();
});
});
}
}
我所做的是对已保存的故事设定承诺,并将任务故事设置为新保存的故事。
即使这解决了我的问题,这是正确的做事方式吗?