0

How can I create a nested/embedded model when creating a record with Ember Data? Specifically, 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')
});

Any ideas on how to do this? I also created a demo on JSBin: http://emberjs.jsbin.com/depiyugixo/edit?html,js,console,output

Thanks!

1 Answer 1

2

Relationships need to be assigned to instantiated models, plain objects won't work.

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return this.store.createRecord('post', {
      title: 'My first post',
      body: 'lorem ipsum ...',
      author: this.store.createRecord('author', {
        fullname: 'John Doe',
        dob: '12/25/1999'
      })
    });
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Note that in order to have author show up in your POST request you'll need DS.EmbeddedRecordsMixin, as detailed in stackoverflow.com/a/45393935/470472.

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.