6
votes

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

4

4 Answers

7
votes

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!

3
votes

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

DS.RESTAdapter.map('App.Post', { comments: { keyName: 'comment_ids' } });
2
votes

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.

0
votes

It appears that this commit is responsible for the situation. When AMS was updated to serialize has_one associations as association_id (bringing AMS into compliance with ember-data), it was also modified to serialize belongs_to associations as association_ids.