Serializers
We use jsonapi-rb for serialization. If you’ve used active_model_serializers before, it will look incredibly familiar:
Would render the JSONAPI Document:
Associations
To add an association:
Assuming there is a corresponding SerializableComment
, you’d see:
Note: Your
Resource
must whitelist this sideload as well.
Customizing Serializers
Occasionally you may need to normalize, format, or elsewise transform
your Model
into an effective JSON representation. To do this, pass a
block to attribute
and reference the underlying @object
being
serialized:
Why not methods like AMS? To avoid collissions with native ruby methods like
tap
.
Keep in mind all serializers have access to @context
- the calling
controller in Rails.
Conditional Fields
You may want to render a field based on runtime context - for instance,
only show the salary
field if the user is a manager. Keeping in mind
that @context
will always be available as the calling controller: