I am having an issue working with Ember Data Fixture Adapter. When saving a record, all of the record\'s hasMany associations are lost. I have created a simple JS Bin to ill
I hit the same problem and came to the same solution. Surely this is a bug in ember-data?
Here's my solution, the only difference is that I'm modifying JSONSerializer, rather than extended RESTSerializer because I'm using the local storage adapter.:
DS.JSONSerializer.reopen({
serializeHasMany : function(record, json, relationship) {
var key = relationship.key;
var relationshipType = DS.RelationshipChange.determineRelationshipType(
record.constructor, relationship);
if (relationshipType === 'manyToNone'
|| relationshipType === 'manyToMany'
|| relationshipType === 'manyToOne') {
json[key] = Ember.get(record, key).mapBy('id');
// TODO support for polymorphic manyToNone and manyToMany
// relationships
}
}
});
Now DS.RelationshipChange is removed. You should use record.constructor like:
record.constructor.determineRelationshipType(relationship)
that show your relation type.
To answer my question, the DS.JSONSerializer.serializeHasMany
seems to only processes and serialize manyToNone and manyToMany relationship types. You can override this behaviour by using a custom serializer for the model:
var get = Ember.get;
App.UserSerializer = DS.RESTSerializer.extend({
serializeHasMany: function(record, json, relationship) {
var key = relationship.key;
var relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship);
if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany' || relationshipType === 'manyToOne') {
json[key] = get(record, key).mapBy('id');
}
}
});
Still not quite sure if this is a bug or if this is the desired/expected behaviour.
This is not a bug, rather a design choice in Ember Data.
The JSONSerializer.serializeHasMany method doesn't serialize manyToOne by design; typically foreign key are persisted on the belongsTo side of the relation, and the hasOne may not persist a foreign key
A work around is explained in this post: http://www.toptal.com/emberjs/a-thorough-guide-to-ember-data see the section "One-to-many and Many-to-one Relationships" the hack is To force DS.hasMany IDs to be serialized as well, you can use the Embedded Records Mixin. like so attrs: {someRelationship: {serialize: 'ids'}}