4
votes

I am using the Ember local storage adapter for an app that has two models: Organizations and Members. The relationship is that Organizations "hasMany" Members, and Members "belongsTo" Organizations, as follows:

App.Org = DS.Model.extend({
  name: DS.attr('string'),
  description: DS.attr('string'),
  members: DS.hasMany('App.Member')
});

App.Member = DS.Model.extend({
  name: DS.attr('string'),
  org: DS.belongsTo('App.Org')
});

In the jsbin of the app, you can add members and the organizations to the local storage, which works perfectly (meaning that when I add a new organization, its selected members are added in the "members" hasMany relationship).

In addition to adding the new organization information, I would like to serialize the newly created organization record to be sent over to a server via AJAX (no I not want to use the RESTAdapter).

However, the "members" hasMany relationship is completely missing from the serialization, so this is the serialization that I'm getting (you can see for yourself if you add some members and then open up the console):

{ 
    name: "Organization name",
    description: "description of the org"
}

and this is the serialization that I would like:

{ 
    name: "Organization name",
    description: "description of the org",
    members: ["id_of_member_1", "id_of_member_2", "id_of_member_3"]
}

This is how I am doing the serialization:

App.OrganizationController = Ember.ArrayController.extend({
    createOrg: function(){
        var neworg = App.Org.createRecord({
          name: this.get('newname'),
          description: this.get('newdescription')
        });
        neworg.get('members').pushObjects(this.get('newmembers'));
        neworg.save();

        var serializer = DS.RESTSerializer.create({});
        console.log(serializer.serialize(neworg));
    }
    ...

If serialization is not the way to go, another way might be making "members" a string array attribute, but so far this path has failed me.

In addition to suggestions, please provide a working jsbin based on the current jsbin of the app. Because I've tried things that don't work.

Keep in mind this app is set up with an Ember Data local storage adapter.

1

1 Answers

0
votes

You can do it with the DS.EmbeddedRecordsMixin. org-serializer.js would look like:

import DS from 'ember-data';

export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    members: { serialize: 'ids' }
  }
});

See the documentation here.