Skip to content

Instantly share code, notes, and snippets.

@slindberg
Last active December 24, 2015 14:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slindberg/6817234 to your computer and use it in GitHub Desktop.
Save slindberg/6817234 to your computer and use it in GitHub Desktop.
Ember data serializer that normalizes embedded records without ids
App.ApplicationSerializer = DS.RESTSerializer.extend({
// Extract embedded relations from the payload and load them into the store
normalizeRelationships: function(type, hash) {
var store = this.store;
this._super(type, hash);
type.eachRelationship(function(attr, relationship) {
var relatedTypeKey = relationship.type.typeKey;
if (relationship.options.embedded) {
if (relationship.kind === 'hasMany') {
hash[attr] = hash[attr].map(function(embeddedHash) {
// Normalize the record with the correct serializer for the type
var normalized = store.serializerFor(relatedTypeKey).normalize(relationship.type, embeddedHash, attr);
// If the record has no id, give it a GUID so relationship management works
if (!normalized.id) {
normalized.id = Ember.generateGuid(null, relatedTypeKey);
}
// Push the record into the store
store.push(relatedTypeKey, normalized);
// Return just the id, and the relation manager will take care of the rest
return normalized.id;
});
}
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment