JSONAPI-Resources / JSONAPI-Resources/jsonapi-resources

Serializing an array of resources

Aperta
#1,100 6 commenti 1 reazione 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Lingua principale
Ruby
Stelle
2.3k
Fork
546
Metriche di merge delle PR
Nessuna PR unita negli ultimi 30g

Descrizione

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?

Guida per i contributori

Nessuna guida per i contributori indicizzata per questo repository

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia con l’esempio di serializer nella documentazione collegata e confrontalo con l’azione index di ProductsController che usa Product.where(visible: true). Verifica come devono essere serializzati gli array di oggetti ProductResource, quindi chiarisci la documentazione per il caso di una collection filtrata; il lavoro è completato quando il workflow degli array è privo di ambiguità.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
rails, ruby
Ambito
backend-api-design, documentation
Tipo di issue
Documentazione
Difficoltà
3/5
Tempo stimato
1-2 giorni
Stato di attività
Ferma
Chiarezza
Da chiarire
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.