Skip to content

Instantly share code, notes, and snippets.

@robmonie
Last active December 20, 2015 01:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save robmonie/6052753 to your computer and use it in GitHub Desktop.
Save robmonie/6052753 to your computer and use it in GitHub Desktop.
WIP: Attempt at fixing the problem in ember data where creating multiple new records at once fails when one new record has a 'belongsTo' relationship to another. This approach is based around applying observers on the ids of records that other records 'belongTo' and only saving them when those records are saved and an id is returned from the ser…
createRecords: function(store, type, records) {
var adapter = this, serializer = this.serializer, initialRecordsToCreate = [];
if (get(this, 'bulkCommit') === false) {
records.forEach(function(record) {
var deferSave = false
record.eachRelationship(function(name, relationship) {
var key = serializer._keyForBelongsTo(record.constructor, name),
child, createDependentRecords;
if (relationship.kind === 'belongsTo') {
if (!serializer.embeddedType(type, name)) {
child = get(record, relationship.key);
createDependentRecords = function() {
adapter.createRecords(store, type, [record]);
child.removeObserver('id', createDependentRecords);
};
if(child && !get(child, 'id')) {
child.addObserver('id', adapter, createDependentRecords);
deferSave = true;
}
}
}
}, this);
if(!deferSave) {
initialRecordsToCreate.push(record);
}
});
return this._super(store, type, initialRecordsToCreate);
}
var root = this.rootForType(type),
plural = this.pluralize(root);
var data = {};
data[plural] = [];
records.forEach(function(record) {
data[plural].push(this.serialize(record, { includeId: true }));
}, this);
return this.ajax(this.buildURL(root), "POST", {
data: data
}).then(function(json) {
adapter.didCreateRecords(store, type, records, json);
}).then(null, DS.rejectionHandler);
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment