Skip to content Skip to sidebar Skip to footer

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 t

Solution 1:

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.


Post a Comment for "How To Add Parent Object To Child In A One-to-may Relationship In Ember Js"