Reputation: 55
This has been asked a couple times, but the examples didn't help a whole lot.
I want to post 'posts' to my server, so I have a 'posts' model and then a 'single' model. The 'posts' model represents all the posts, and then my 'single' model represents what each post needs... I am new to Ember.js, and really could use a hand here/direction.
So when I submit the form (for creating a new post):
// 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
}
'posts' model:
import DS from 'ember-data';
export default DS.Model.extend({
posts: DS.hasMany('single'),
});
'single' model: import DS from 'ember-data';
export default DS.Model.extend({
title: DS.attr('string'),
content: DS.attr('string'),
});
And then my serializer to hook the two together...
import DS from 'ember-data';
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
posts: { embedded: 'always' }
}
});
Currently, this is the error that outputs:
"Assertion Failed: All elements of a hasMany relationship must be instances of DS.Model, you passed [[object Object]]"
In Short: I need to create data models that can represent the following JSON structure:
{
"posts": [
{ "title": "Title", "content": "Content" }
]
}
Thanks!
Upvotes: 1
Views: 806
Reputation: 35501
The error is actually saying exactly what's wrong.
"Assertion Failed: All elements of a hasMany relationship must be instances of DS.Model, you passed [[object Object]]"
The model posts
has a hasMany
relationship to the model single
.
What your code is doing is passing a plain JS object instead of the model.
const data = {
"posts": [
{ // <-
"title": title, // <-
"content": content // <- this is a POJO
} // <-
]
};
One way to solve this actually is to create the two objects separately.
// 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);
Upvotes: 1