这已被问过几次,但这些例子并没有太大帮助。
我想将“帖子”发布到我的服务器,所以我有一个“帖子”模型,然后是一个“单一”模型。 “帖子”模型代表所有帖子,然后我的“单个”模型代表每个帖子需要什么......我是 Ember.js 的新手,真的可以在这里/方向使用。
因此,当我提交表单(用于创建新帖子)时:
// When the form is submitted, post it!
actions: {
// createNew begin
createNew() {
var title = this.controller.get('title');
var content = this.controller.get('content');
const data = {
"posts": [
{
"title": title,
"content": content
}
]
};
return this.store.createRecord('posts', data).save().
then(function(post) {
console.log(post);
}, function(error) {
console.log(error);
});
} // end of createNew
}
“帖子”模型:
import DS from 'ember-data';
export default DS.Model.extend({
posts: DS.hasMany('single'),
});
“单一”模型:
从“ember-data”导入 DS;
export default DS.Model.extend({
title: DS.attr('string'),
content: DS.attr('string'),
});
然后我的序列化程序将两者 Hook ......
import DS from 'ember-data';
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
posts: { embedded: 'always' }
}
});
目前,这是输出的错误:
“断言失败:hasMany 关系的所有元素都必须是 DS.Model 的实例,您传递了 [[object Object]]”
总而言之 :我需要创建可以表示以下 JSON 结构的数据模型:
{
"posts": [
{ "title": "Title", "content": "Content" }
]
}
谢谢!
最佳答案
该错误实际上是在说明问题所在。
"Assertion Failed: All elements of a hasMany relationship must be instances of DS.Model, you passed [[object Object]]"
型号
posts
有一个 hasMany
与模型的关系single
.您的代码正在做的是传递一个普通的 JS 对象而不是模型。
const data = {
"posts": [
{ // <-
"title": title, // <-
"content": content // <- this is a POJO
} // <-
]
};
实际上解决这个问题的一种方法是分别创建两个对象。
// create 'posts' and 'single' separately
const posts = this.store.createRecord('posts');
const single = this.store.createRecord('single', {
title,
content
});
// link them up
posts.get('posts').addObject(single);
关于javascript - Ember 数据中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42422991/