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

余生长醉 提交于 2019-12-07 03:15:05

问题


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


回答1:


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!




回答2:


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

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



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/14633432/has-many-configuration-for-ember-data-and-active-model-serializers-with-embedded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!