1

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'}}
fvisticot
  • 7,936
  • 14
  • 49
  • 79

1 Answers1

2

Try this:

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

If that doesn't work try:

author: Ember.belongsTo('App.Author', { key: 'author', embedded: true})
ianpetzer
  • 1,828
  • 1
  • 16
  • 21
  • I have tested and it does not work. If I'm correct belongsTo is the reverse side of the relation... – fvisticot Aug 19 '13 at 20:19
  • Ember-model only has belongsTo and hasMany relationship types. There is no hasOne like Rails. Are you using the RESTAdapter? What does your JSON look like? Also updated my answer to show how to specify the key for the Author id. – ianpetzer Aug 19 '13 at 20:34
  • I have upadated my question with JSON sample – fvisticot Aug 19 '13 at 20:43
  • ok.. the author is embedded, not a separate JSON payload. I've updated my answer.. Hope that helps – ianpetzer Aug 19 '13 at 21:15