Search code examples
ember-model

OneToOne relationship with ember-model


How to implement a one to one relationship with ember-model ?

I have tried the following code but it does not work.

App.Book = Ember.Model.extend({
  id: Ember.attr(),
  title: Ember.attr(),
  name: Ember.attr(),
  author: App.Author
});

App.Author = Ember.Model.extend({
  id: Ember.attr(),
  firstName: Ember.attr(),
  lastName: Ember.attr()
});

I have also tried the next code but I get an error when I try to set the author with the next code:

Error: You must use Ember.set() to access this property (of )

var book = App.Book.create({
  author: App.Author.create({firstName: 'fred'})
});

App.Book = Ember.Model.extend({
      id: Ember.attr(),
      title: Ember.attr(),
      name: Ember.attr(),
      author: Ember.attr(App.Author)
    });

I'm using the RESTAdapter and my JSON looks like:

{title: 'booktitle', name: 'thename', author: {firstName: 'fred', lastName: 'last'}}

Solution

  • Try this:

    author: Ember.belongsTo('App.Author', {embedded: true})
    

    If that doesn't work try:

    author: Ember.belongsTo('App.Author', { key: 'author', embedded: true})