How can I create a record with a nested record in Ember Data?


#1

I want to create a post model with a nested/embedded model author. The following code gives me the error:

Error while processing route: index Assertion Failed: You cannot add a ’undefined’ record to the ‘post.author’. You can only add a ‘author’ record to this relationship. Error: Assertion Failed: You cannot add a ’undefined’ record to the ‘post.author’. You can only add a 'author’ record to this relationship.

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return this.store.createRecord('post', {
      title: 'My first post',
      body: 'lorem ipsum ...',
      author: {
        fullname: 'John Doe',
        dob: '12/25/1999'
      }
    });
  }
});

App.Post = DS.Model.extend({
  title: DS.attr('string'),
  body: DS.attr('string'),
  author: DS.belongsTo('author')
});

App.Author = DS.Model.extend({
  fullname: DS.attr('string'),
  dob: DS.attr('string')
});

#2
return this.store.createRecord('post', {
  title: 'My first post',
  body: 'lorem ipsum ...',
  author: this.store.createRecord('author', {
    fullname: 'John Doe',
    dob: '12/25/1999'
  })
});

#3

Thanks @jasonmit! So If I have a big blob of JSON with nested data, I’d have to manually call this.store.createRecord for all the nested objects?

What if a post has many comments?

{
      title: 'My first post',
      body: 'lorem ipsum ...',
      author: {
        fullname: 'John Doe',
        dob: '12/25/1999'
      },
     comments: [ 
        { desc: 'some description 1' }, 
        { desc: 'some description 2' } 
     ]
}

#4

@skaterdav85 did you figure this one out? I’m searching for a solution for the same problem. A new (parent) record is being created that will have multiple new records. When the parent record is created, it will also create the other records on the server side.


#5

@Garrick If each of the nested objects is considered a resource and you want to treat it as a model, you will have to store.createRecord for each one. However, if you are creating a single resource and the backend happens to expect some attributes with nested objects, then no, you don’t need to do that. Creating a bunch of different types of resources at once doesn’t really fit into the typical REST semantics.