Rails + Ember:嵌套模型格式不正确

时间:2017-06-22 00:35:51

标签: ruby-on-rails serialization ember.js rails-api

我有一个Rails API,我试图在Ember中提取记录,而在其工作时,我的嵌套模型不是。我有一个Employee belongs_to一个Location,并创建了一个类似的序列化程序:

class API::EmployeeSerializer < ActiveModel::Serializer
  attributes :id, :name, :phone, :email, :manager, :terminated, :location
  belongs_to :location
end

输出:

{"employee":
    {"id":19,"name":"John Abreu","phone":"","email":"","manager":false,"terminated":false,"location":
        {"name":"Peabody","id":2}
    }
}

我的余烬应用程序通过以下方式提取:

从&#39; ember&#39;;

导入Ember
export default Ember.Route.extend({
    model() {
        return this.store.findAll('employee')
    }
});

但是当我遇到散列的location部分时,我遇到了错误。我得到以下内容:

> Assertion Failed: Ember Data expected the data for the location
> relationship on a <employee:19> to be in a JSON API format and include
> an `id` and `type` property but it found {name: Peabody, id: 2}.
> Please check your serializer and make sure it is serializing the
> relationship payload into a JSON API format.

我该如何纠正?我已经拥有LocationSerializer

class LocationSerializer < ActiveModel::Serializer
  attributes :id, :phone, :address, :name
end

1 个答案:

答案 0 :(得分:1)

我需要做的就是在位置哈希中添加type属性。根据{{​​3}}类型,应采用以下格式:

{
  "data": {
    "type": "articles",
    "id": "1",
    "attributes": {
      // ... this article's attributes
    },
    "relationships": {
      // ... this article's relationships
    }
  }
}

所以我将LocationSerializer修改为以下内容:

class LocationSerializer < ActiveModel::Serializer
  attributes :id, :phone, :address, :name, :type

  def type
    return "location"
  end
end