Ember.JS ActiveModelAdapter和Active Model Serializers的默认行为

时间:2014-02-25 01:25:36

标签: ember.js ember-data active-model-serializers

我有一个简单的活动模型序列化器:

class ActivitySerializer < ActiveModel::Serializer
  attributes :id, :title, :description, :time
  has_one :category
  has_one :user
end

我也有类别和用户序列化程序,它们按预期工作。我得到了这个有效载荷:

{"activities":[{"id":1,"title":"Test Activity","description":null,"time":"2014-03-01T06:05:41.027Z","category":{"id":1,"title":"Sports"},"user":{"id":1,"name":"ember"}}]}

然而,它们似乎并没有加载到余烬中。

App.Activity = DS.Model.extend
  title: DS.attr('string')
  description: DS.attr('string')
  time: DS.attr('date')
  category: DS.belongsTo('category')
  user: DS.belongsTo('user')

App.Category = DS.Model.extend
  title: DS.attr('string')
  activities: DS.hasMany('activity')

App.User = DS.Model.extend
  name: DS.attr('string')
  activities: DS.hasMany('activity')

当我检查ember检查器时,未加载数据。 ActiveModelSerializer期望什么样的格式?它加载活动但不加载类别或用户属性。

2 个答案:

答案 0 :(得分:7)

这个技巧让我有点在网上找到,我的模型需要包含embed :ids

class ActivitySerializer < ActiveModel::Serializer
  embed :ids, include: true

  attributes :id, :title, :description, :time
  has_one :category
  has_one :user
end

或者,您可以按照没有承诺来执行某些事情 我从未测试过此代码。

App.ActivitySerializer = DS.ActiveModelSerializer.extend DS.EmbeddedRecordsMixin,
  attrs:
    user: {embedded: 'always'}
    category: {embedded: 'always'}


App.ApplicationAdapter = DS.ActiveModelAdapter.extend
  defaultSerializer: 'DS/app'

答案 1 :(得分:3)

Ryan提到的嵌入id是有效的,但是你可能会遇到变形问题,例如organized_by变为有组织的,然后你必须配置双方来纠正它。解决此问题所需的JS代码是:

DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: { category: {embedded: 'always'} }
});