How to validate nested structs and arrays
A Planting holds several seedlings, one has a leaf count that is out of range, and you need to say which.
1. Declare the shape
Section titled “1. Declare the shape”A struct class works as a type, so a field can hold one, and :array with of: holds a list. Hashes passed in for them are built into structs.
class Seedling < FieldStruct::Base required :species, :string required :leaves, :integer, in: 1..99end
class Planting < FieldStruct::Base required :label, :string required :seedlings, :array, of: Seedling optional :showpiece, Seedlingend
planting = Planting.new(label: 'P7', seedlings: [{ species: 'fern', leaves: 12 }, { species: 'moss', leaves: 0 }])2. Read the parent’s verdict
Section titled “2. Read the parent’s verdict”One invalid child makes the parent invalid. The parent says so once, on the field, and doesn’t name the element.
planting.valid? # => falseplanting.errors.to_h # => {seedlings: ["is invalid"]}planting.seedlings.first.valid? # => true3. Find the element
Section titled “3. Find the element”errors.paths names the element and the field inside it:
planting.errors.paths # => {"seedlings[1].leaves" => ["is invalid"]}Every element is also a struct with its own errors, so you can ask each one, for a report shaped your own way:
bad = planting.seedlings.each_with_index.reject { |seedling, _| seedling.valid? }bad.map(&:last) # => [1]
report = planting.seedlings.each_with_index.to_h { |s, i| [i, s.errors.to_h] }.reject { |_, errors| errors.empty? }report # => {1 => {leaves: ["is invalid"]}}The "element at index 1 is invalid" message belongs to plain elements checked through element: options, like strings with a format:. A struct element reports through itself instead.
4. Re-assign after changing a child in place
Section titled “4. Re-assign after changing a child in place”Validity gets computed when a value is assigned (see Validity is computed on assignment). If you change a child later, the parent doesn’t notice, whichever way the change goes.
planting.seedlings[1].leaves = 3# Still stale: the parent kept the verdict from the last assignment.planting.valid? # => false
planting.seedlings = planting.seedlingsplanting.valid? # => trueAssigning the field again runs coercion and validation again. with does too, and it hands back a new object:
Planting.new(label: 'P7', seedlings: [{ species: 'fern', leaves: 12 }]).with(label: 'P8').label # => "P8"See also
Section titled “See also”FieldStruct, Actionable and their adapters are open source under the MIT license.