I'm trying to understand how to save a many-to-many relationship in Ember. And for this purpose, I've set up a JS Bin with a Firebase backend to play around in.
In this example, one blog post can have many authors. And one author can create many blog posts. Here are the models:
App.Post = DS.Model.extend({
msg: DS.attr(),
authors: DS.hasMany('user', { async: true }),
});
App.User = DS.Model.extend({
name: DS.attr(),
posts: DS.hasMany('post', { async: true })
});
Here, I'm simply playing around with hard-coded data. I want to save a blog post and two authors. Then I want to add the associated 'post' record to the users' table.
So, here's how my non-working, 'savePost; function looks:
savePost: function(){
var post = this.store.createRecord('post',{msg: 'round the rugged rock'});
var author1 = this.store.createRecord('user', {name: 'john'});
var author2 = this.store.createRecord('user', {name: 'jane'});
post.save()
//please ignore the fact that author saving happens inside saving a post
//I just needed it to demonstrate what I want to do
.then(function(){
author1.save();})
.then(function(){
author2.save();})
.then(function(){
post.get('authors').addObjects(author1, author2)
.then(function(){
post.save();
});
});
}
Am I supposed to be using the Ember Embedded Records mixin for this?
If so, could you please show the usage and syntax for this?
Aucun commentaire:
Enregistrer un commentaire