9
votes

I'm using Ember data and having a hard time figuring out get ember to recognize nested properties in my JSON response from the server. This is ember-1.0.0-pre.4.js.

Currently, I've set up associated models with Ember data revision 11. Here the

# School Model
App.School = DS.Model.extend
  addr:       DS.belongsTo('App.Addr')

  name:       DS.attr 'string'
  status:     DS.attr 'string'

# Address Model
App.Addr = DS.Model.extend
  school:   DS.belongsTo 'App.School'

  line1:    DS.attr 'string'
  city:     DS.attr 'string'
  state:    DS.attr 'string'
  iso:      DS.attr 'string'

And here is the JSON response from my server:

{"schools":
 [{
    "_id":"51020261bbc3b8c526000007",
    "name":"Willamette",
    "status":"p",
    "addr":{
      "line1":"122 Evergreen Terrace",
      "city":"Springfield",
      "state":"IL",
      "iso":"US"
    }
   }    
  ]}

My adapter is set up as follows:

    App.Store = DS.Store.extend
      revision: 11
      adapter: DS.RESTAdapter.create({
        url: "http://localhost:8000/api"
        serializer: DS.RESTSerializer.extend
        primaryKey: (type) ->
          '_id';
      }) 

UPDATE: I've tried to map the addr property, as follows. Still no dice...

DS.RESTAdapter.map 'App.School', 
  addr: { embedded: 'always'}

In my template, I'd like to do something like this...

   <script type="text/x-handlebars" data-template-name="school">
      <h2>School: {{name}}</h2>
      <p> Status: {{ status }}</p>
      <p> Address: {{ addr.line1 }} {{ addr.city }} </p>
    </script>

The name and status properties render fine. But addr.line1 and addr.city are blank. Is there a way to get Ember to recognize the nested addr propeties?

Thanks!

3
match post as answeredlesyk

3 Answers

6
votes

Since you're embedding the addr JSON in your schools JSON you need to setup the mapping in the DS.RESTAdapter.

DS.RESTAdapter.map 'App.School',
  addr: { embedded: 'always' }

The embedded option can have two values, 1) always, 2) load.

See Yehuda's answer here for the details: https://stackoverflow.com/a/14324532/1409279

6
votes

Did you get time to look at

Ember Data: Model Fragments

It allows nested data

2
votes

Looks like sma's answer was correct, I just needed a reference to the adapter first. This bit...

DS.RESTAdapter.map 'App.School', addr {embedded: 'always' }

...gives an error 'cannot call map of undefined'. So updated to...

    App.Adapter = DS.RESTAdapter.extend
      bulkCommit: false


    App.Adapter.map 'App.School', {
      addr: {embedded: 'always'}
    }

Works now!