I am implement a discussion forum in my Ember App. I use Ember-Data with RESTAdapter for accessing the backend. I have a post model and a thread model. Thread can hasMany root posts. When I create new thread, I need to create thread and the root post.
I tried to create new record of thread with new record of post embedded and it didn’t work. Ember replaced the post with null. So when i called save on thread, I only saved the thread without any realtionship (and also no post).
What is the correct way to save thread and a post? Or what is the correct way of saving multiple models with non-trivial relationships?
Save the children first. Funny how this sounds like a protocol for abandoning a ship Here’s an example:
var store = this.store;
var post = store.createRecord('post', { title: 'First post!' });
post.save().then(function() {
return store.createRecord('thread', { title: 'New thread', posts:[post] }).save();
});
In my last project I created a mixin that extends an ED model with saveRelationships() & rollbackRelationships() methods. If you think about the model and its relationships it’s a tree. I would recursively traverse the tree and save leaf nodes first. Works perfectly with async properties too. This makes saving even the deeply nested models a breeze. To translate that to your case:
Is ember-data a hard requirement? We had this same need (for embedded POST) and manage the relationship(s) ourselves (allowing any type of ajax POST/etc).
Beyond creating /managing the one-to-many relationship yourself you need to decide on a primary key strategy. We elected to have ember generate a true uuid value (so when we POST we already have a PK value for both parent/and nested models)
If you can’t do this it becomes increasingly more difficult as you need to use something like a “temp” pk until the backend resolves/ then “flip” the pks to reflect what is truly persisted on the server.