[dry-validation 1.0] rule key path syntax with array

Hello!

I’m upgrading dry-validation in our app to 1.0 and am running into issues with key path syntax when one of the params is an array. The schema looks like this:

params do
  optional(:rooms).array(:hash) do
    required(:guests).array(:hash, GuestSchema)
  end
end

Now if I want to validate for example that number of guests in each room has to be 2 how would I go about writing a rule to catch that? I thought it would be a simple case of rule(rooms: :guests), but that raises rule specifies keys that are not defined by the schema: [{:rooms=>[:guests]}].

Looks like you hit this bug so try to use rule('rooms.guests') { ... } instead. I’ll fix it in the meantime.

Thanks @solnic, but I’m afraid this is something else. The error message is different and the proposed solution doesn’t work for me. I think the difference is that I’m using an array of hashes rather than just a hash.

OK so in 1.1.0 this will be possible:

require 'dry/validation'

class C < Dry::Validation::Contract
  params do
    optional(:rooms).array(:hash) do
      required(:guests).array(:integer)
    end
  end

  rule(:rooms).each do
    key.failure('must have 2 guests') if key? && value[:guests].equal?(2)
  end
end

contract = C.new

puts contract.call(rooms: [{ guests: [1, 2] }, { guests: [3] }]).errors.to_h.inspect
# {:rooms=>{1=>["must have 2 guests"]}}

I’ll be releasing it shortly.

That’s great news, thank you!