【问题标题】:Rails + Ember: Nested models incorrect formatRails + Ember:嵌套模型格式不正确
【发布时间】:2017-11-25 01:50:21
【问题描述】:

我有一个 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}
    }
}

我的 ember 应用程序通过以下方式实现了这一点:

从“ember”导入 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

【问题讨论】:

  • 尝试在属性中将:location更改为:location_id
  • 不走运,它正确地包含了:location_id,但仍然包含了发生错误的location 哈希

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


【解决方案1】:

我需要做的就是将type 属性添加到位置哈希。根据JSONAPI.org 类型应为以下格式:

{
  "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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多