Use JSON schema validation in ActiveRecord
masterUse the json: validator in your ActiveRecord models to validate JSON attributes against a schema. The schema can be a path to a JSON file, a Ruby Hash, or a JSON string.
If the JSON data itself is malformed (invalid JSON), the validator provides a helper method named {attribute}_invalid_json to retrieve the raw invalid string.
class User < ActiveRecord::Base
PROFILE_JSON_SCHEMA = Rails.root.join('config', 'schemas', 'profile.json')
validates :profile, presence: true, json: { schema: PROFILE_JSON_SCHEMA }
end
user = User.new(name: 'Samuel Garneau', profile: { city: 'Quebec City' })
user.valid? # => false
user = User.new(name: 'Samuel Garneau', profile: '{invalid JSON":}')
user.valid? # => false
user.profile_invalid_json # => '{invalid JSON":}'