# Polymorphic schema for a sub-hash in dry-validation

**URL:** <https://discourse.dry-rb.org/t/polymorphic-schema-for-a-sub-hash-in-dry-validation/995>\
**Category:** dry-validation\
**Created:** [February 4, 2020, 11:42pm UTC](https://discourse.dry-rb.org/t/polymorphic-schema-for-a-sub-hash-in-dry-validation/995 "2020-02-04T23:42:15Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![joekhoobyar](https://yyz1.discourse-cdn.com/flex031/user_avatar/discourse.dry-rb.org/joekhoobyar/32/481_2.png) [@joekhoobyar](https://discourse.dry-rb.org/u/joekhoobyar)\
**Post date:** [February 4, 2020, 11:42pm UTC](https://discourse.dry-rb.org/t/polymorphic-schema-for-a-sub-hash-in-dry-validation/995/1 "2020-02-04T23:42:15Z")

</div>

I’m trying to support a “polymorphic” schema for sub-hashes using dry-validation.

I couldn’t find any documentation on this capability, and I ended up hacking something together that seems… ugly.

There has got to be a better way to do this.

```
require 'dry-validation'

class ParentContract < Dry::Validation::Contract
  json do
    optional(:child).hash
  end

  rule :child do
    case value[:type]
    when 'special'
      child_contract = SpecialChildContract.new
    else
      child_contract = ChildContract.new
    end

    child_contract.call(value).errors.each do |message|
      body = message.meta.empty? ? message.text : {text: message.text, meta: message.meta}
      key([:child] + message.path).failure(body)
    end
  end
end

class ChildContract < Dry::Validation::Contract
  json do
    required(:type).value(:string)
    required(:name).value(:string)
    optional(:description).value(:string)
  end
end

class SpecialChildContract < ChildContract
  json do
    required(:foobar).value(:string)
  end
end

c1 = ChildContract.new
p c1.call(type: 'generic', name: 'abc').errors.to_h

c2 = SpecialChildContract.new
p c2.call(type: 'special', name: 'abc', description: 1234).errors.to_h

h = ParentContract.new
p h.call(child: { type: 'special', name: 'abc', description: 1234}).errors.to_h
```

---

<div class="post-metadata">

**Author:** ![solnic](https://yyz1.discourse-cdn.com/flex031/user_avatar/discourse.dry-rb.org/solnic/32/779_2.png) [@solnic](https://discourse.dry-rb.org/u/solnic)\
**Post date:** [February 9, 2020, 2:24pm UTC](https://discourse.dry-rb.org/t/polymorphic-schema-for-a-sub-hash-in-dry-validation/995/2 "2020-02-09T14:24:18Z")

</div>

Inheritance is not fully supported yet, especially when it comes to rails-specific concepts like STI and its `type` attribute. We’ll get there eventually but for now you need to stick to quick’n’dirty hacks like yours.
