1
votes

Two of the models in my application are projects and users. Projects can have many users assigned to them and vice versa. I'm using Ember Data, so my model looks like this:

App.Project = DS.Model.extend({
  name: DS.attr('string'),
  created: DS.attr('date'),
  users: DS.hasMany('App.User')
});

When creating a project on the server, the API expects to receive the project's name AND an array of IDs corresponding to the project's users. So, basically, something like this:

POST /projects
{
  project: {
    name: 'My Project',
    users: [1, 10, 14]
  }
}

However, Ember Data isn't including the array of user IDs when sending a POST or PUT request. By default, it only includes the name attribute. How can I modify Ember Data to include what I need? Is it even worth doing, or should I go the Discourse route and abandon Ember Data for now?

1

1 Answers

2
votes

Assuming you are using the latest version and the RESTAdapter/RESTSerializer, you can override the addHasMany method of the serializer.

So, here is an example of how to do this:

App.CustomSerializer = DS.RESTSerializer.extend({
  addHasMany: function(hash, record, key, relationship) {
    var ids = record.get(relationship.key).map(function(item) {
      return item.get('id');
    });

    hash[relationship.key] = ids;
  },
});

App.Store = DS.Store.extend({
  adapter: DS.RESTAdapter.extend({
    serializer: App.CustomSerializer.create()
  })
});

Note that the addHasMany implementation is taken from https://github.com/emberjs/data/blob/master/packages/ember-data/lib/serializers/fixture_serializer.js#L41