Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error message is not parsed properly #38

Open
nav16 opened this issue May 23, 2018 · 2 comments
Open

Error message is not parsed properly #38

nav16 opened this issue May 23, 2018 · 2 comments

Comments

@nav16
Copy link

nav16 commented May 23, 2018

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
Copy link
Author

nav16 commented May 23, 2018

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

@remi
Copy link
Member

remi commented May 24, 2018

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants