Is there a way to manually serialize a collection?

2.2k Views Asked by At

I'd like to manually serialize a collection for testing purposes. I tried this:

JSONAPI::ResourceSerializer.new(PostResource).
  serialize_to_hash(PostResource.new(Post.all))

This doesn't work. It appears you can only serialize a single resource here. How would one return a serialized collection of all posts?

3

There are 3 best solutions below

0
On

Another way to manually serialize data, based on JSONAPI Resources features, is by using the jsonapi-utils gem:

With the jsonapi_serialize method:

class API::V1::UsersController < API::V1::BaseController
  def index
    users = User.all 
    render json: jsonapi_serialize(users)
  end
end

Or the high-level jsonapi_render method:

class API::V1::UsersController < API::V1::BaseController
  def index
    jsonapi_render json: User.all
  end
end

Hope it's useful for you :-)

0
On

If you are using ActiveModelSerializers (https://github.com/rails-api/active_model_serializers)

Try to do helper like this:

def serialize_resource(resource)
  JSON.parse(ActiveModelSerializers::SerializableResource.new(resource).to_json)
end

You can use this pattern both for one resource or many resources. In your case it will be:

JSON.parse(ActiveModelSerializers::SerializableResource.new(Post.all).to_json)
0
On

I was trying the same thing - but it is not possible. JSONAPI::Resource does not have any helper to easily convert Relation object or array of records into JSONAPI::Resource instances, so you can't pass the collection like this.

serialize_to_hash expects array of JSONAPI::Resource, so you would have to do something horrible like this:

result = []
Post.all.each do |post|
  result << PostResource.new(post)
end

JSONAPI::ResourceSerializer.new(PostResource).serialize_to_hash(result)

JSONAPI::Resources expects that the JSONAPI itself should be sufficient, so no implementation of methods like index should be needed - gem will handle it itself without the need for manual serialization. But it is true, that I can imagine some scenarios, where I would want to be able to mannualy serialize collection of records, so there should be some easy way to do this...unfortunately, It looks like there is no easy way for now.

UPDATE: I had some further questions myself so I have asked the creators of the gem here: https://github.com/cerebris/jsonapi-resources/issues/460