0

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.?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. The REST server is a developed with php/zend/apigility what follows REST HAL specs out of the box and the shown format is the way to push data to the server. I think it makes absolutely sense to be able to push related records with one request and have them processed by the server within the same roundtrip. In my case I have a form with company data and address data. This is one form but two related entities. If I weren't able to post them together I would need two ajax calls what I think is not very convenient. Any suggestions are welcome.
It is just what I`m used to do as RoR Ember developer but if you need something like this and its what your server expects then just use this if you need twiddle pls let me know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.