Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

has_many configuration for Ember-Data and Active Model Serializers with embedded IDs and sideloading

I know that Ember-Data is supposed to be compatible with Active Model Serializers by design, but they seem to be out of step on serializing has_many relationships with embedded IDs.

For example, the serializer

class PostSerializer < ActiveModel::Serializer
  embed :ids
  has_many :comments
end

produces the JSON

{
    "post": {
        "comment_ids": [...]
    }
}

But the default configuration in Ember Data,

App.Post = DS.Model.extend({
  DS.hasMany('App.Comment'),
});

App.Comment = DS.Model.extend();

expects the comments association to be serialized as comments: [...] without the _ids suffix (see the relationships sub-section of the REST adapter section of the Ember.js guide).

I tried the following as a work-around:

class PostSerializer < ActiveModel::Serializer
  attribute :comments
  def comments
    object.comment_ids
  end
end

It works, but adding embed :ids, :include => true in order to enable side-loading now does nothing since AMS doesn't know that it's an association.

Edit: I am using the active_model_serializers (0.6.0) gem and Ember-Data revision 11

like image 598
ahmacleod Avatar asked Jan 31 '13 19:01

ahmacleod


3 Answers

For ember-data 1.0.0-beta.3 I ended up using this:

App.ApplicationSerializer = DS.ActiveModelSerializer.extend({});

As explained here: Transition Guide

Works very nicely!

like image 77
bfcoder Avatar answered Sep 30 '22 01:09

bfcoder


You can try to configure the right mapping in the adapter at the client side

DS.RESTAdapter.map('App.Post', { comments: { keyName: 'comment_ids' } });
like image 27
ken Avatar answered Sep 30 '22 00:09

ken


I'm using active_model_serializers 0.6.0 and ember_data 11. I don't see behaviour you are reporting.

My serializer:

class CentreSerializer < ActiveModel::Serializer
  embed :ids

  attributes :id, :name
  has_many :rooms
end

The output of localhost:3000/centres/1.json

{
  centre: {
    id: 1,
    name: "Centre0",
    rooms: [
      1,
      2,
      3,
      4,
      5
    ]
  }
}

In my case the rails app is producing the correctly formed json before it even gets across to ember. You shouldn't have to resort to mapping on the client side.

like image 45
Martin Stannard Avatar answered Sep 30 '22 01:09

Martin Stannard