JSONAPI-Resources / JSONAPI-Resources/jsonapi-resources

Serializing an array of resources

Open
#1,100 6 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Ruby
Stars
2.3k
Forks
546
PR merge metrics
No merged PRs in 30d

Description

The documentation shows a clear example on how to do it for one resource:

post = Post.find(1)
JSONAPI::ResourceSerializer.new(PostResource).serialize_to_hash(PostResource.new(post, nil))

But how does one serialize an array of resources?

For example, suppose this is my controller:

class ProductsController < ApplicationController
  def index
    @products = Product.where(visible: true)
    render json: JSONAPI::ResourceSerializer.new(ProductResource).serialize_to_hash(ProductResource.new(@products, nil))
  end
  def show
    product = Product.find(params[:id])
    render json: JSONAPI::ResourceSerializer.new(Admin::ProductResource).serialize_to_hash(ProductResource.new(product, nil))
  end
end

GET /products/2
The show method returns 1 resource in JSON API compliant format. Even better, I could remove the entire show method and it will still work because the inherited methods do something similar.

GET /products/
However, the index method returns a 500 error. Removing the index method entirely would partially solve the problem, I get an array back containing ALL products. But what if I need it to return only the active=true products? For that I need an array serializer no?

Suggestions?
Am I missing something?
Is the documentation incomplete?
Have I perhaps not understood how to work with JSON API? I've got the impression the idea is to not add any logic to your controllers at all and let the URLs do all the work?

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the serializer example in the linked documentation and compare it with the ProductsController index action using Product.where(visible: true). Verify how arrays of ProductResource objects are intended to be serialized, then clarify the documentation for the filtered collection case; done means the array workflow is unambiguous.

Written by the indexing model from the issue text.

Assessment

Tech stack
rails, ruby
Domain
backend-api-design, documentation
Issue type
Documentation
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.