As seems to be the case with most everything I do with ember-data the simple test case is very simple but anything "real" falls apart quickly due to my lack of understanding (and I think documentation). In the simplest case I have no problem creating a new record and saving it to my REST API. I'll use the prevalent fruit basket example and start with just saving a new piece of fruit
.
// Here is our fruit model
module.exports = App.Fruit= DS.Model.extend({
name: attr('string'),
color: attr('string')
});
// This is easy to create and save
var fruit = this.store.createRecord('fruit', {
name: 'apple',
color: 'red'
});
fruit.save().then(successCallback, errorCallback);
Okay, I have no problem here. Conceptually makes sense, the code is clean, and things look peachy! Now suppose that we have a basket
model and that basket
model can hold lots of fruit
. Furthermore, the user can create new fruit
and add it to a new basket
that has not been created yet in one step from the UI.
So here are the new models:
module.exports = App.Fruit= DS.Model.extend({
name: attr('string'),
color: attr('string')
basket: DS.belongsTo('basket')
});
module.exports = App.Basket = DS.Model.extend({
fruits: DS.hasMany('fruit', {async:true})
});
Given the above, lets say the user inputs in two new fruits that don't currently exist in the store or in the backend REST API, adds them to his new basket (which also doesn't exist yet) and then hits 'save'.
How do you create this record using Ember Data? I was hoping you could do something like this:
var newFruits = Ember.A();
newFruits.pushObject(this.store.createRecord('fruit', {
name: 'orange',
color: 'orange'
}));
newFruits.pushObject(this.store.createRecord('fruit', {
name: 'banana',
color: 'yellow'
}));
var basket = this.store.createRecord('basket', {
fruits: newFruits
});
basket.save().then(successCallback, errorCallback);
Unfortunately, this doesn't seem to work. When I look at the POST request data in Chrome inspector the fruits
property of basket is always empty. Basically, the request ends up looking this:
{
basket: {
fruits: []
}
}
Am I using the correct pattern to create the 'basket' record? I'm hoping I don't have to end up saving each piece of fruit first before saving the basket as it seems wasteful to send 3 POST requests when 1 would suffice. Additionally, what happens when the user wants to create 10 pieces of fruit? That would be 11 POST Requests.
Is there a standard practice for accomplishing the above? Essentially, how do you create a new record with a hasMany relationship (basket) where the records in the hasMany relationship are also new (the fruit).
Thank you!
Here are the versions I am using:
-------------------------------
Ember : 1.3.2+pre.25108e91
Ember Data : 1.0.0-beta.7+canary.238bb5ce
Handlebars : 1.3.0
jQuery : 2.0.3
-------------------------------