2
votes

I am unable to save parent records in a hasMany/belongsTo relationship. When I save the record, it forgets who its children are.

The objects are defined like so:

        // We're using ember-data...
        MF.Store = DS.Store.extend({
            adapter: DS.FixtureAdapter
        });

        // Two objects, a parent...
        MF.Parent = DS.Model.extend({
            name: DS.attr(),
            childs: DS.hasMany('child')
        });
        MF.Parent.FIXTURES = []; // ...with fixtures

        // ...and a child
        MF.Child = DS.Model.extend({
            name: DS.attr(),
            parent: DS.belongsTo('parent')
        });
        MF.Child.FIXTURES = [];

I have tried the following order of operations with the same end results in each.

  • Set Child's Parent. Save the Child. Save the Parent
  • Set Child's Parent. Save the Parent.
  • Add Child to Parent. Save Parent.
  • Add Child to Parent. Save Child. Save Parent.

There's a live demo you can see here on GitHub.

1
I'm seeing the same issue; pretty much the same setup. I'm hoping this works when using the REST adapter, but at the moment, I am just changing the relationship and via set and this automatically updates my UI without calling save. - steakchaser

1 Answers

0
votes

Looks like this is a known bug: http://discuss.emberjs.com/t/ember-data-fixture-adapter-saving-record-loses-has-many-relationships/2821

Here's the fix they suggest. It appears to be working.

MF.jsonSerializer = DS.JSONSerializer.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] = Ember.get(record, key).mapBy('id');
            // TODO support for polymorphic manyToNone and manyToMany
            // relationships
        }
    }
});

Then I just specify the serializer for the models I need it in:

MF.ParentSerializer = MF.jsonSerializer;
MF.Childerializer = MF.jsonSerializer;