18
votes

I am really stuck with tons of problems caused by Ember-data and it lacks of embedded records support.

I have searched the entire web, most of the posts are outdated others are outdated + requires me to use 3rd party libraries or to wire up 300 lines of special code with lots of drawbacks.

I've no idea how to use embedded records with ember-data as it stands today?

edit: there is a new documentation now http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html

1

1 Answers

31
votes

Using the ActiveModelSerializer you can include the EmbeddedRecordsMixin which allows you to use embedded records. (In the canary versions, 1.0 beta 9+, you can use the JsonSerializer/RESTSerializer as well)

Serializer

App.ColorSerializer = DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    foos: {embedded: 'always'}
  }
});

Models

App.Color = DS.Model.extend({
  color: DS.attr(),
  foos: DS.hasMany('foo')
});

App.Foo = DS.Model.extend({
  name: DS.attr()
});

JSON

{
 colors:[
  {
    id: 1,
    color: "red",
    foos:[
      {
        id:1,
        name:'something 1'
      },
      {
        id:2,
        name:'something 2'
      }
    ]
  },
  ...

http://emberjs.jsbin.com/qagalabaso/1/edit

For the RESTSerializer and JsonSerializer it follows the same pattern

App.ColorSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    foos: {embedded: 'always'}
  }
});

http://emberjs.jsbin.com/lesiwebobi/1/edit