I have two models.
App.Request = DS.Model.extend({
materials: DS.hasMany('App.Material')
});
App.Material = DS.Model.extend({
request: DS.belongsTo('Mat.Request')
});
In the form for creating a request, I create a new request:
App.Request.createRecord();
And bind it to the fields of the form. To create a new material, you click a button and a modal appears. When the modal appears, it creates a new material in the materials array of the request: (The material modal has its own controller, so I have to get the request by going to the RequestsNewController.)
this.get('controllers.requestsNew.materials').createRecord();
Yay! It works. I can add many materials to the request and the UI is updating to show that the associations are being created correctly. Awesome! Until... I hit the save button, calling this code from the RequestsNewController:
this.get('transaction').commit();
Now, the materials I've added to my request are torn away (the part of the template that shows the materials in the request now shows no materials.)
This is a very simplified version of my code, but the point is that everything looks good until I commit the data to the server. I have a theory as to what's happening, but I have no idea how to fix it! I'm using Rails with Active Model Serializers on my backend, by the way.
When I call commit, the Rest Adapter first POSTs to /requests. The record is added, and I get the following back from the server:
{
"request": {
"id": 30,
"material_ids": []
}
}
Yay! My request has been saved, and I now have an ID from the server.
Next, the REST Adapter POSTs to /materials and it sends the following JSON:
{
"material": {
"request_id": 0,
}
}
And the server responds, giving the material an ID.
But what's this? The REST Adapter is sending request_id: 0, not request_id: 30 like it should?
Here's my theory: After the request is saved, the server responds with an empty array of material_ids. This makes sense! We haven't sent the materials to the server yet because we need the request ID first! However, when Ember Data sees an empty array of material_ids, it removes the materials from the request. Then, when the materials save, they no longer have a request, hence request_id: 0.
When I create a request with no materials, commit, add materials, commit, it works!
What am I doing wrong?
Thanks!