Serializer
The ResourceSerializer
can be used to serialize a resource into JSON API compliant JSON. ResourceSerializer
must be initialized with the primary resource type it will be serializing. ResourceSerializer
has a serialize_to_hash
method that takes a resource instance or array of resource instances to serialize. For example:
post = Post.find(1) |
Note: If your resource needs access to state from a context
hash, make sure to pass the context
hash as the second argument of the resource class’s new
method. For example:
post = Post.find(1) |
This returns results like this:
{ |
Options
The ResourceSerializer
can be initialized with some optional parameters:
include
An array of resources. Nested resources can be specified with dot notation.
Purpose: determines which objects will be side loaded with the source objects in an included
section
Example: include: ['comments','author','comments.tags','author.posts']
fields
A hash of resource types and arrays of fields for each resource type.
Purpose: determines which fields are serialized for a resource type. This encompasses both attributes and relationship ids in the links section for a resource. Fields are global for a resource type.
Example: fields: { people: [:email, :comments], posts: [:title, :author], comments: [:body, :post]}
post = Post.find(1) |