georoot
georoot

Reputation: 3617

Storing emberjs hasMany model on server?

So here is the model structure that i currently have in place

// match.js
import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),
    match: DS.attr('number'),
    players: DS.hasMany('player')
});
//player.js
import DS from 'ember-data';

export default DS.Model.extend({
    pid: DS.attr('number'),
    match: DS.attr('number'),
    name: DS.attr('string'),
    point: DS.attr('number'),
    home: DS.attr('boolean'),
    squard: DS.belongsTo('squard'),
    selected: DS.attr('boolean', {default: false})
});

I create a new squad on client side and use push playerss using the following code

let player - this.store.peekRecord('player', id);
let squard = this.store.peekRecord('squard', 1);
squard.get('players').pushObject(player);

I tried using squard.save() but that doesn't send the array of players with it. How can i push those changes to server ?

Upvotes: 0

Views: 42

Answers (2)

jelhan
jelhan

Reputation: 6338

Using DS.EmbeddedRecordsMixin as suggested by Trenton Trama's answer should only be used together with DS.RESTSerializer, which is not the default one.

If using DS.JSONAPISerializer, which implements JSON API specification and used as default, customizing shouldSerializeHasMany() is a way better approach.

Have in mind that there are good reasons not to do a full replacement of has-many relationships. A JSON API compliant server might not support it at all:

Note: Since full replacement may be a very dangerous operation, a server may choose to disallow it. For example, a server may reject full replacement if it has not provided the client with the full list of associated objects, and does not want to allow deletion of records the client has not seen. (Source)

Upvotes: 1

Trenton Trama
Trenton Trama

Reputation: 4930

If you want to push the full list of players to the server when you save a squad, you will want to use the ember embedded-records mixin.

Create a squad adapter and add the following to it.

import DS from 'ember-data';

export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    players: { embedded: 'always' }
  }
});

This will cause the players array to be serialized and included in the squad payload.

Upvotes: 2

Related Questions