A simple validator to validate jsonb
columns against a JSON schema. It's dependent on
the json-schema gem, make sure to add gem 'json-schema'
to your Gemfile and run $ bundle
.
To use this, add json_validator.rb
to app/models/concerns
and json_validator_spec.rb
to spec/models/concerns
. By
convention, schemas are stored in app/models/json_schemas
.
The following example illustrates a model Post
that has a tags
attribute. Using the JsonValidator
and the
tags_attribute.json
schema it ensures that tags
is only valid if it's an array of strings.
The Post model
in app/models/post.rb
class Post < ApplicationRecord
validates_with Validators::JsonValidator, attribute: :tags, schema: :tags_attribute
end
Tags attribute schema
in app/models/json_schemas/tags_attribute.json
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Tags",
"description": "A list of tags",
"type": "array",
"items": {
"type": "string"
}
}
Note: You can omit $schema
, title
, and description
.