Search code examples
javascriptember.jsember-data

How to save nested objects in ember js


In a related question I wanted to know How to add parent object to child in a one-to-many relationship in ember.js. Now I want to know how to simultaneously save them on the server when creating or updating the parent with a newly created child.

The server would expect something like this:

parent {
    prop1: 'val1',
    prop2: 'val2',
    child: {
        prop1: val1
        prop2: val2
    } 
}

but ember's payload looks like this:

parent {
    prop1: 'val1',
    prop2: 'val2',
    child:null
}

The same goes for updates when having an already existing child appended to the parent. Then the payload looks something like this:

parent {
    prop1: 'val1',
    prop2: 'val2',
    child:2
}

So it's not the child-object transferred with the payload but only it's id if existing (otherwise null)). Is it possible to send a nested object like the server expects or do I have to save both models separately with two ajax-post/put-requests.?


Solution

  • I`m not sure why is your server is expecting something like that but you can achieve it like this.

    first on your parent model you put

    child: DS.attr("") //this will give you ability to send any type in your case object to property child.
    

    then where you create child

      this.store.createRecord('parent',{
          child: this.store.createRecord('child',{name: "John"})
      });
    

    or if you have something like this

    let parent = this.store.findRecord("parent", 1);
    let child = this.store.createRecord('child',{name: "John"});
    parent.set("child", child);
    

    Personally I would avoid it but you can do in js what ever you want.