How to add relations with local adapter / serializer of storage data Ember Data to hasMany?

I use the local Ember storage adapter for an application that has two models: organizations and members. The relationship is that the members of the "hasMany" Organization and the members "belong" to the organizations:

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 application you can add members and organizations to the local storage, which works fine (which means that when I add a new organization, its selected members are added to the hasMany members "relations").

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

However, the "members" of the hasMany relationship are completely absent from serialization, so this is the serialization that I get (you can see for yourself if you add some elements, and then open the console ):

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

and this is the serialization I need:

 { 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 do 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 suitable, another way could make the "members" an attribute of a string array, but so far this way has not helped me.

In addition to the suggestions, please provide a working jsbin based on the current jsbin application . Because I tried things that do not work.

Remember that this application is configured using the local Ember Data adapter.

+4
source share
1 answer

You can do this with DS.EmbeddedRecordsMixin . org-serializer.js will look like this:

 import DS from 'ember-data'; export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { members: { serialize: 'ids' } } }); 

See the documentation here .

0
source

Source: https://habr.com/ru/post/1492842/


All Articles