Search code examples
javascriptember.jsember-data

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.


Solution

  • Basically this works as you expect. But you have a few minor errors:

    • Sometimes you use child and sometimes child-object. Same goes for parent.
    • findRecord returns a PromiseObject. You probably want to wait for the promise to resolve.
    • Its not addObject.

    Also you can do it from both sides. Either set the parent:

    this.store.findRecord('parent-object', 2).then(parent => {
      const child = this.store.createRecord('child-object');
      child.set('parent', parent);
    });
    

    Or you add the child to the children:

    this.store.findRecord('parent-object', 2).then(parent => {
      const child = this.store.createRecord('child-object');
      parent.get('children').pushObject(child);
    });
    

    Maybe check out this twiddle.