activerecord_json_validator icon indicating copy to clipboard operation
activerecord_json_validator copied to clipboard

Error message is not parsed properly

Open nav16 opened this issue 6 years ago • 2 comments

I am using it in a engine core, on Rails 5.2.0

validates :children, json: { schema: CHILDREN_SCHEMA }

I am not getting proper error message

"children": [
            "translation missing: en.activerecord.errors.models.core/user.attributes.children.invalid_json"
        ]

After adding :message option

validates :children, json: { message: ->(errors) { errors }, schema: CHILDREN_SCHEMA }

The error message is:

"children": [
            "The property '#/0' did not contain a required property of 'gender' in schema file:///Users/navneet/rails_app/components/core/app/models/schemas/children.json"
        ]

Is there any way to change the message format similar to:

"children": [
        "0": {
            "gender property missing"
        }
    ]

Any suggestions will be helpful.

nav16 avatar May 23 '18 16:05 nav16

I think customising the error is not possible as the message is generated by json-schema json-schema/required

nav16 avatar May 23 '18 17:05 nav16

Yes you’re right, the default error message is invalid_json, which is then translated by ActiveRecord.

The way you’re using the message option is correct — you could pass the errors argument through a custom method to parse errors into a structured hash:

class Foo < ApplicationRecord
  validates :children, json: { message: ->(errors) { Foo.parse_json_errors(errors) }, schema: CHILDREN_SCHEMA }

  def self.parse_json_errors(errors)
    # Here, you can parse the `errors` array into something more meaningful
  end
end

I hope this helps you!

remi avatar May 24 '18 22:05 remi