EJIqpEP9
EJIqpEP9

Reputation: 69

How to get user object with belongs_to in ember js?

I have two models Recipe and User. I can't get the user object in recipe. What am I doing wrong?

App.Recipe.find(1).get('title') // Returns "recipe01 title". All works fine.

App.Recipe.find(1).get('user') // Returns null

user.js.coffee

App.User = DS.Model.extend
   email: DS.attr('string')
   recipes: DS.hasMany('App.Recipe')

recipe.js.coffee

App.Recipe = DS.Model.extend
  user: DS.belongsTo('App.User')
  title: DS.attr('string')

my json array

{
  recipe: {
    id: 1,
    title: "recipe01",
    user: {
      id: 1,
      name: "ejiqpep",
      email: "[email protected]",
    }
  }
}

Upvotes: 2

Views: 544

Answers (1)

Bradley Priest
Bradley Priest

Reputation: 7458

By default Ember Data expects dependent records to be referenced by key. Then you can either sideload the extra records or let Ember lazy load them from their API endpoint.

{
  recipe: {
    id: 1,
    title: "recipe01",
    user_id: 1
  },
  user: {
    id: 1,
    name: "ejiqpep",
    email: "[email protected]"
  }
}

However, you can also instruct the Adapter that the records are embedded.

There are two types of embedded record loading embedded: 'always', where Ember will both receive and send any changes with the objects embedded.

App.Adapter.map 'App.Recipe',
  user: 
    embedded: 'always'

Or embedded:'load' where Ember will load embedded objects from JSON but will save changes back to the API as separate objects.

App.Adapter.map 'App.Recipe',
  user:
    embedded: 'load'

Which of the three options you'd like to take is up to you. Embedded objects have only recently been implemented and there are a couple of issues around them (see the Ember-Data issues on Github), but will work without any changes to your existing server.

Upvotes: 3

Related Questions