How to handle nested json responses with ember?

Maybe I’m overlooking something, but I from can’t figure out how I’m supposed to do that

I have a JSON coming from the server which looks like this

{
  "articles": [
    {
      "user": {
        "name": "user",
        "username": "user",
        "_id": "52755cba74a1fbe54a000002"
      },
      "_id": "5275698c53da846e70000001",
      "__v": 0,
      "content": "content",
      "title": "title",
      "created": "2013-11-02T21:07:24.554Z"
    }
  ]
}

In the template, I’m accessing content and created fine, but when I try to get user.name, nothing comes out:

	{{#each article in model}}
	    {{ article.title }}
	    by {{ article.user.name }}
	    {{ article.created }}
	{{/each}}

I noticed that in the model, whatever I don’t define, won’t appear in the template, so it looks like this:

    title: DS.attr('string'),
    content: DS.attr('string'),
    created: DS.attr('date')

But when I try to add:

user: {
       name: DS.attr('string')
}

To match the nested json, I get an error.

Is ember not able to handle nested json? If it is, then how?

Thanks.

The rewrite of ember-data removed support for embedded records. The latest beta build adds support back, so you need to be using it.

First, the way you defined the embedded record is totally wrong. You need to define user attribute on articles as a relation to another model definition:

user: DS.belongsTo('user')

Then, you need to use a custom serializer with the Embedded Records Mixin to load embedded records for the model type:

App.ArticlesSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
    attrs: {
         users: { embedded: 'always' }
    }
}):
1 Like

Thank you. Where are the docs or guide which explains these details?

I found this bit in here about defining relationships on the client side. Defining Models - Ember Data - Ember Guides

To what benefit is it to have to strictly define it like this? I wonder if there are examples of how to put this to good use.

The rest serializer and mixins I can’t find explained anywhere…

I believe this functionality is in the Beta build only, so the documentation on emberjs.com won’t show it. If you read through the ember-data source code you will see documentation for embedded data.