Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember-data embedded records current state?

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

like image 410
kfir124 Avatar asked Jun 14 '14 17:06

kfir124


1 Answers

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

like image 149
Kingpin2k Avatar answered Oct 27 '22 01:10

Kingpin2k