If an optional value is true, I want to add another optional value to the schema. The following doesn’t work as intended. If I pass
{ setting_is_allowed: true, setting: 200 }
setting is not returned in the output. I was trying to build a rule, but I couldn’t find enough examples to piece together the exact scenario I am dealing with.
optional(:setting_is_allowed).maybe.when(:true?) do
optional(:setting).maybe {none? | int?}
end
@solnic, hi, I didn’t find answer anywhere. My question is very similar to this one.
define do
optional(:lat).filled(:float)
optional(:lng).filled(:float)
end
I have schema above(I use only dry-schema). This 2 params optional, but if at least 1 of them present, second is also required. How can I implement this? Thanks.
If I had to guess, this probably falls more into the realms of dry-validation than it doesn’t into dry-schema.
Hence, defining some dry-validation contract that looks like:
class SomeContract < Dry::Validation::Contract
params do
optional(:lat).filled(:float)
optional(:lng).filled(:float)
end
rule(:lat, :lng) do
key(:lat).failure(:filled?) if values[:lng] && !values[:lat]
key(:lng).failure(:filled?) if values[:lat] && !values[:lng]
end
end
Aside:
I do think that having dependent fields might make sense to define at schema level.