Hi.
I have this form( dry-validation 0.11):
Form = Dry::Validation.Schema(BaseForm) do
optional(:scopes).maybe do
array? do
each do
hash? do
required(:scope_id).filled(:int?, :scope_exists?)
required(:objectives).filled(:array?, min_size?: 1) do
array? do
each(:int?)
end
end
end
end
end
end
#scope_exists?
method simple checks if there is record in db.If yes, then it raises error: “is not available”. Consider this input data:
{
scopes:
[
{
scope_id: 1,
objectives: ["1", :b, 1]
},
{
scope_id: 121,
objectives: ["string", [], 1]
}
]
}
Lets assume that there is already record in table Scopes with id = 1. When I do: Form.call(data).errors.to_h
I receive following errors:
{
:scopes => {
0 => {
:scope_id => ["is not available"],
:objectives => {
0 => ["must be an integer"], 1 => ["must be an integer"]
}
},
1 => {
:objectives => {
0 => ["must be an integer"], 1 => ["must be an integer"]
}
}
}
}
Now I have to re-write this form in dry-validation 1.6 but I am having problems. Keep in mind that I want to get same errors as in dry-validation 0.11.
At first I thought I can do something like this(dry-validation 1.6)
class Form < BaseForm
params do
optional(:scopes).maybe(:array) do
each do
hash? do
required(:scope_id).filled(:integer)
required(:objectives).filled(:array, min_size?: 1) do
each(:integer)
end
end
end
end
end
rule(:scopes).each do |index:|
key([:scopes, index, :scope_id]).failure(:scope_exists?) unless scope_exists?(value[:scope_id])
end
end
However, when I do: Form.new.call(data).errors.to_h
I get:
{ :scopes => { 0 => { :scope_id => ["is not available"] } } }
I don’t get any errors regarding invalid types in objectives array like I get in dry-validation 0.11.
I eventualy achieve the same error structure with this rather verbose code:
rule(:scopes).each do |index:|
if !value.keys.include? :scope_id
key([:scopes, index, :scope_id]).failure("is missing")
elsif value[:scope_id].nil?
key([:scopes, index, :scope_id]).failure("must be filled")
elsif !value[:scope_id].is_a?(Integer)
key([:scopes, index, :scope_id]).failure("must be an integer")
else
key([:scopes, index, :scope_id]).failure(:scope_exists?) unless scope_exists?(value[:scope_id])
end
if !value.keys.include? :objectives
key([:scopes, index, :objectives]).failure("is missing")
elsif value[:objectives].nil?
key([:scopes, index, :objectives]).failure("must be filled")
elsif !value[:objectives].is_a?(Array)
key([:scopes, index, :objectives]).failure("must be an array")
elsif value[:objectives].size < 1
key([:scopes, index, :objectives]).failure("size cannot be less than 1")
else
value[:objectives].each_with_index do |obj_value, obj_index|
key([:scopes, index, :objectives, obj_index]).failure("must be an integer") unless obj_value.is_a?(Integer)
end
end
end
Is this a bug?Am I am missing something?Do you know how Can I get errors like I get in 0.11 version?
Thanks in advance.