I am well aware it can be done and I\'ve looked at quite a few places (including: Best practice for saving an entire collection?). But I\'m still not clear \"exactly how\"
The answer depends on what you want to do with the collection on server side.
If you have to send additional data with the post you might need a wrapper model or a relational model.
With the wrapper model you always have to write your own parse method:
var Occupants = Backbone.Collection.extend({
model: Person
});
var House = Backbone.Model.extend({
url: function (){
return "/house/"+this.id;
},
parse: function(response){
response.occupants = new Occupants(response.occupants)
return response;
}
});
Relational models are better I think, because you can configure them easier and you can regulate with the includeInJSON option which attributes to put into the json you send to your rest service.
var House = Backbone.RelationalModel.extend({
url: function (){
return "/house/"+this.id;
},
relations: [
{
type: Backbone.HasMany,
key: 'occupants',
relatedModel: Person,
includeInJSON: ["id"],
reverseRelation: {
key: 'livesIn'
}
}
]
});
If you don't send additional data, you can sync the collection itself. You have to add a save method to your collection (or the collection prototype) in that case:
var Occupants = Backbone.Collection.extend({
url: "/concrete-house/occupants",
model: Person,
save: function (options) {
this.sync("update", this, options);
}
});