我在我的项目中使用 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
我现在需要以expected_payments
json api 格式返回。所以据我了解,我应该使用序列化程序
我这样做
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))
这适用于数组中的第一个对象。
文档说“有ResourceSerializer
一种serialize_to_hash
方法可以将资源实例或资源实例数组序列化。”
如何让它与一组资源实例一起工作?我在文档中看不到任何示例。