Kris
Kris

Reputation: 89

Ember data stripping hasMany relationship

I am having a terrible time with this, but I have the following action on a controller:

saveOrganization: function() {  
  var org = this.get('model');
  var users = org.get('users').then(function() {
    console.log(org); //users are a part of org
    org.save(); //users are not sent to server
  });
}

and associated organization model:

export default DS.Model.extend({
  createdAt: DS.attr('date'),
  updatedAt: DS.attr('date'),
  name: DS.attr('string'),
  address: DS.attr('string'),
  city: DS.attr('string'),
  state: DS.attr('string'),
  zip: DS.attr('string'),
  users: DS.hasMany('user',{async:true}),
  totalUsers: function() {
    return this.get('users').get('length');
  }.property('users.@each')
});

and associated users model:

export default DS.Model.extend({
    createdAt: DS.attr('date'),
    updatedAt: DS.attr('date'),
    name: DS.attr('string'),
    email: DS.attr('string'),
    bio: DS.attr('string'),
    picture: DS.attr('string'),
    organization: DS.belongsTo('organization'),
    type: DS.attr('string'),
    username: DS.attr('string'),
    password: DS.attr('string')
});

As you can see from the comments, when I get the users array as part of the organization, I can see the data, but when I save it, ember data never sends the users array as part of the data sent to the server.

Can anyone help me figure out what might be going on?

Thanks.

Upvotes: 2

Views: 110

Answers (1)

Kingpin2k
Kingpin2k

Reputation: 47367

Stack over flow won't let me mark this as a dupe of Serialize ids when saving emberjs model, but it really is. Ember Data is stupid in this aspect, if it's a ManyToOne relationship, it only includes the id from the belongsTo side.

https://github.com/emberjs/data/commit/7f752ad15eb9b9454e3da3f4e0b8c487cdc70ff0#commitcomment-4923439

App.ApplicationSerializer = DS.RESTSerializer.extend({

 serializeHasMany: function(record, json, relationship) {
    var key = relationship.key;
    var payloadKey = this.keyForRelationship ? this.keyForRelationship(key, "hasMany") : key;
    var relationshipType = RelationshipChange.determineRelationshipType(record.constructor, relationship);

    if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany'
        || relationshipType === 'manyToOne') {  // This is the change
      json[payloadKey] = get(record, key).mapBy('id');
      // TODO support for polymorphic manyToNone and manyToMany relationships
    }
  },
});

Upvotes: 1

Related Questions