【发布时间】: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))
我得到<NoMethodError: undefined method 'id' for <Array:0x005642734fa6f8>>
然后我尝试了:
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