Serializers
We use jsonapi-rb for serialization. If you’ve used active_model_serializers before, it will look incredibly familiar:
# app/serializers/serializable_post.rb
class SerializablePost < JSONAPI::Serializable::Resource
type :posts
attribute :title
attribute :description
attribute :body
end
Would render the JSONAPI Document:
{
data: {
type: "posts",
id: "123",
attributes: {
title: "My Post",
description: "Some description",
body: "Blah blah blah"
}
}
}
Associations
To add an association:
has_many :comments
Assuming there is a corresponding SerializableComment
, you’d see:
{
data: {
type: "posts",
id: "123",
attributes: { ... },
relationships: {
comments: {
data: [
{ id: "1", type: "comments" }
]
}
}
},
included: [
{
type: "comments",
id: "1"
}
]
}
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:
attribute :title do
@object.title.upcase
end
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:
attribute :salary, if: -> { @context.current_user.manager? }