dry-rb / dry-schema

Coercion and validation for data structures
https://dry-rb.org/gems/dry-schema
MIT License
415 stars 108 forks source link

Incorrect key validation for schemas in `maybe(:array)` #455

Open yauhenininjia opened 1 year ago

yauhenininjia commented 1 year ago

Describe the bug

Basically it is a reopening of the issue described (and reported as fixed) in https://github.com/dry-rb/dry-schema/issues/300

Valid keys of nested optional array set via maybe(:array).each(schema) are reported as incorrect. It occurs in latest version 1.13.0 as well

To Reproduce

NestedSchema = Dry::Schema.define do
  required(:bar).filled(:string)
end

BrokenSchema = Dry::Schema.define do
  config.validate_keys = true
  required(:foo).maybe(:array).each(NestedSchema)
end

BrokenSchema.call({ foo: [{ bar: "bar" }] }).errors.to_h

#=> {:foo=>{0=>{:bar=>["is not allowed"]}}}

Expected behavior

errors for the snippet above are empty

My environment

JacobAlexander commented 1 year ago

Use Dry::Schema.Params

NestedSchema = Dry::Schema.define do
  required(:bar).filled(:string)
end

BrokenSchema = Dry::Schema.Params do
  required(:foo).maybe(:array).each(NestedSchema)
end

BrokenSchema.call({ foo: [{ bar: 123 }] }).errors.to_h
# => {:foo=>{0=>{:bar=>["must be a string"]}}}

BrokenSchema.call({ foo: [{ bar: '123' }] }).errors.to_h
# => {}