4

I am using the json api resource gem in my project.

I have setup a simple resource

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

In my controller I get an array of ExpectedPayments objects from a service

expected_payments = CreateExpectedPayments.new(registration_params).call

I now need to return the expected_payments in the json api format. So from what I understand, I should use the serializer

I do this

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

And I get <NoMethodError: undefined method 'id' for <Array:0x005642734fa6f8>>

And then I tried:

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

And that worked for the 1st object in the array.

The documentation says "ResourceSerializer has a serialize_to_hash method that takes a resource instance or array of resource instances to serialize."

How do I get it to work with an array of resource instances? I can't see any examples in the documentation.

David North
  • 437
  • 1
  • 4
  • 17

1 Answers1

-3

If you are using Rails. Please try active_model_serializer which brings convention over configuration to your JSON generation.

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

Yon can stop wronging how you can generate a JSON response once you start using AMS.

Below is the getting start guide for AMS,

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

XY L
  • 25,431
  • 14
  • 84
  • 143