Why hasMany isn't sent to backend while save?


#1

Hi,

I have a model that looks like this:

export default DS.Model.extend({
  title: DS.attr( 'string' ),
  parent: DS.belongsTo( 'category', { async: true, inverse: 'children' } ),
  children: DS.hasMany( 'category', { async: true, inverse: 'parent' } )
});

If I do model.save() within my controller the payload looks like this (the model has children):

category: {
  title: 'XX',
  parent: 'Z'
}

Does someone has an idea?


#2

Hi Dennis,

I believe that you’ll need to use the EmbeddedRecordsMixin in your Serializer. For example, your serializer (assuming that you’re using the ActiveModelSerializer) would look like this:

import DS from 'ember-data';

export default DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    children: { serialize: 'records', deserialize: 'ids' }
  },  
});

#3

What zaid is correct. The standard is that you save the parent_id on the child (for a hasMany relation). so you would need to save the childs as well to save the relation.

Ember.RSVP.all([ cild1.save(), child2.save(), ... ])

Also you can tell Ember to embed the relation in the payload.

category: {
    childs: [ {id:1, name: 'test'}, {id:2, ...} ]
}

Or you tell ember to only serialize id’s on the parent .

category: {
    child_ids: [ 1,2,3 ],
    parent_id: 2
}

It might be best to read through this: http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html

As said… The standard (I hope Im still correct with that) is at a 1:n relation that you save the parent_id on the child. Any other way needs to be set up.

Hope that helps


#4

First thank you for your help, but I think that there is another problem.

I use the RESTAdapter with the standard RESTSerializer. If I save any other model that has a hasMany relationship, then the hasMany property exists in payload but here it looks like this:

The children property isn’t there. Does this problem exist only because of “inverse: true”?


#5

hmm, odd. I think you dont need to add the inverse… its meant to differ types of relations of the same kind.