InvalidModel Serializer
You are using one of the many ruby json_api serializer gems like active_model_serializers or fast_jsonapi, but are not satisfied with the rendering of validation errors?
This gem is trying to fit this gap.
Usage
Add the gem to your Gemfile
gem 'invalid_model-serializer'To generate a json-api compliant error hash simply call
InvalidModel::Serializer.new(invalid_model).serializable_hashWhich should parse your ActiveModel compatible errors and produce something like:
{
"errors": [
{
"code": "validation_error/too_short",
"detail": "Name is too short (minimum is 6 characters)",
"meta": {
"count": 6
},
"source": {
"pointer": "/data/attributes/name"
},
"status": "400"
}
]
}Rails
In a rails controller you could for example use:
def create
...
if @record.save
head :no_content
else
render json: InvalidModel::Serializer.new(@record).serializable_hash, status: :bad_request
end
endOptions
You can pass options to the serializer as 2nd argument. The following keys are supported:
-
code_format: Override the default format. This string will be passed through aformatmethod so you can use some placeholders liketypeandattribute. -
status: Set a different status, default is400 -
each_serializer: Use your own serializer for error objects.
Configuration
Additionally you can set code_format and status globally via:
InvalidModel::Serializer.configure do |config|
config.default_code_format = 'validation_error/%{model}.%{attribute}.%{type}'
config.default_status = '422'
end