3
votes

Maybe I'm overlooking something, but I from can't figure out how I'm supposed

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}}
        <span>{{ article.title }}</span>
        <span>by {{ article.user.name }}</span>
        <span>{{ article.created }}</span>
    {{/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.

3

3 Answers

5
votes

This might be the easiest way to support embedded documents (if you don't want to change your JSON):

App.ArticleSerializer = DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    user: {embedded: 'always'}
  }
})

See: http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html. I haven't tested it though!

3
votes

As mentioned there are heavy changes to embedded records since Ember Data 1.0 beta 1 and there is no more support for it. If you need embedded records you could have a look at ember-data-extensions project: https://github.com/pixelhandler/ember-data-extensions It provides support for embedded record by an EmbeddedAdapter and EmbeddedRecordMixins.

A simple implementation example:

App.ApplicationAdapter = DS.EmbeddedAdapter.extend({});

App.ApplicationSerializer = DS.EmbeddedSerializer.extend();

App.Article = DS.Model.extend({
    user: DS.belongsTo('user'),
    content: DS.attr('string'),
    title: DS.attr('string'),
    created: DS.attr('date')
});

App.User = DS.Model.extend({
    name: DS.attr('string'),
    username: DS.attr('string'),
    articles: DS.hasMany('article')
})

App.ArticleSerializer = App.ApplicationSerializer.extend({
    attrs: {
        user: {embedded: 'always'}
    }
});

But you should be aware that there is no support for embedded records only on load yet.

1
votes

According to the transition guide; Ember data doesn't support embedded records yet.

https://github.com/emberjs/data/blob/master/TRANSITION.md#embedded-records

There is an example of how to implement it yourself. Another option is to use ember-model, it supports embedded associations. I am sorry I don't have an example.