【问题标题】:Json Api Resources | response with array of objectsJson API 资源 |对象数组的响应
【发布时间】:2017-07-02 19:51:36
【问题描述】:

我在我的项目中使用 json api 资源 gem。

我已经设置了一个简单的资源

module V1
  class ExpectedPaymentResource < JSONAPI::Resource
    attributes :registration_id, :invoiced_amount_due, :date_due, :status, :created_at, :updated_at
  end
end

在我的控制器中,我从服务中获得了一组 ExpectedPayments 对象

expected_payments = CreateExpectedPayments.new(registration_params).call

我现在需要以 json api 格式返回 expected_payments。所以据我了解,我应该使用serializer

我这样做

render json: JSONAPI::ResourceSerializer.new(ExpectedPaymentResource).serialize_to_hash(ExpectedPaymentResource.new(expected_payments, nil))

我得到&lt;NoMethodError: undefined method 'id' for &lt;Array:0x005642734fa6f8&gt;&gt;

然后我尝试了:

render json: JSONAPI::ResourceSerializer.new(ExpectedPaymentResource).serialize_to_hash(ExpectedPaymentResource.new(expected_payments[0], nil))

这适用于数组中的第一个对象。

documentation 表示“ResourceSerializer 有一个 serialize_to_hash 方法,该方法采用资源实例或资源实例数组进行序列化。”

如何让它与一组资源实例一起工作?我在文档中看不到任何示例。

【问题讨论】:

    标签: ruby-on-rails api json-api jsonapi-resources


    【解决方案1】:

    如果您使用的是 Rails。请尝试使用 active_model_serializer,它为您的 JSON 生成带来了约定优于配置。

    https://github.com/rails-api/active_model_serializers

    一旦您开始使用 AMS,您就可以停止错误地生成 JSON 响应的方式。

    以下是 AMS 的入门指南,

    https://github.com/rails-api/active_model_serializers/blob/master/docs/general/getting_started.md

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      • 2019-01-29
      • 2019-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多