Reputation: 3561
I am using jsonapi to render an object:
product = Product.find(1)
render json: ProductSerializer.new(product)
My question is, how should I serialize a list of products?
If I do this:
products = Product.all
render json: ProductSerializer.new(products)
It doesn't work, I get this error (which makes sense because I am trying to serialize an array and it doesn't have an id):
id is a mandatory field in the jsonapi spec
And If I serialize each product and return it in an array, like this:
response = []
products = Product.all
products.each do |product|
response << ProductSerializer.new(product)
end
Each object will have an included
object, instead of having just one included
appended to the response with all relationships...
And this is the ProductSerializer
:
class ProjectSerializer
include JSONAPI::Serializer
set_type :product
attributes :name
end
Upvotes: 0
Views: 1080
Reputation: 1
render json: serialize(products)
def serialize(data, serializer = ProductSerializer) serializer.new(data).serializable_hash[:data].map { |hash| >hash[:attributes]} end
Upvotes: 0