mardi 18 avril 2017

How to add parent object to child in a one-to-may relationship in ember js

I have two models in ember.js with a one-to-may relationship. Now I want to create a new child object and need to assign an associated parent object. I can't figure out how to do this. My models are defined with the following code:

model of parent-object

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),
    children: DS.hasMany('child')
});

model of child-object

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),
    parent: DS.belongsTo('parent')
});

In the model()-method of the route create a child object.

var child = this.store.createRecord('child');

and then query for the parent-object.

var parent = this.findRecord('parent', 2);

Then I tried to bind them together but anythig I tried failed. For example:

parent.get('child').addObject(child) // or
parent.get('child').pushObject(child) // or
child.set('parent', parent)

These things result in parent not having anything in child and child not having anything in parent. I also did some attempts with async promise resolving but with no success. It would be great if someone could post an example how to manage this.




Aucun commentaire:

Enregistrer un commentaire