Dry-validation how to allow array of hashes with nil value

119 views Asked by At

This is how I'm trying to allow a nil value for an array of hashes (Im using dry-validations gem)

required(:properties).maybe(:array).each(:hash)

This is raising the following exception:

NoMethodError: undefined method `map' for nil:NilClass
from /Users/svelandiag/.rbenv/versions/2.6.6/lib/ruby/gems/2.6.0/gems/dry-logic-1.2.0/lib/dry/logic/operations/each.rb:15:in `call'

How to allow a nil value in this case?

1

There are 1 answers

2
svelandiag On BEST ANSWER

Well it actually took me a bit of time, but the answer seems to be here https://dry-rb.org/gems/dry-schema/1.9/basics/macros/#maybe

You cannot use maybe with each, you should do this instead:

required(:properties).maybe(:array) do
  nil? | each(:hash)
end

It took me a decent amount of time to find the answer since I was looking at the "Nested Data" section within dry-schema docs, I would suggest that if some contributor of the project is seeing this, please add a similar section to explain that maybe and each are not compatible in the "Nested Data" section of the dry-schema docs https://dry-rb.org/gems/dry-schema/1.9/nested-data/