这已被问过几次,但这些例子并没有给出太多帮助。
我想发布帖子'到我的服务器,所以我有一个'帖子'模特,然后一个单一的'模型。 '帖子' model表示所有帖子,然后我的单个' model代表每个帖子需要的东西......我是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';
导入DSexport default DS.Model.extend({
title: DS.attr('string'),
content: DS.attr('string'),
});
然后我的序列化器把两者连在一起......
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" }
]
}
谢谢!
答案 0 :(得分:1)
错误实际上是说错了。
“断言失败:hasMany关系的所有元素必须是DS.Model的实例,您传递[[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);