# Reusing schema by switch required to optionsl

**URL:** <https://discourse.dry-rb.org/t/reusing-schema-by-switch-required-to-optionsl/265>\
**Category:** dry-validation\
**Created:** [May 10, 2017, 8:16am UTC](https://discourse.dry-rb.org/t/reusing-schema-by-switch-required-to-optionsl/265 "2017-05-10T08:16:42Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![mkristian](https://avatars.discourse-cdn.com/v4/letter/m/22d042/32.png) [@mkristian](https://discourse.dry-rb.org/u/mkristian)\
**Post date:** [May 10, 2017, 8:16am UTC](https://discourse.dry-rb.org/t/reusing-schema-by-switch-required-to-optionsl/265/1 "2017-05-10T08:16:42Z")

</div>

I do have these to schema and beside the required and optional they are the same. the reason is when creating this object all of the mare required but to patch the object any given parameter is OK.

```auto
 Dry::Validation.Schema do
    required(:name).filled(:str?)
    required(:begin_date).filled(:date?)
    required(:energyprice_cents_per_kilowatt_hour).filled(:float?)
    required(:baseprice_cents_per_month).filled(:int?)
  end

  Dry::Validation.Schema do
    optional(:name).filled(:str?)
    optional(:begin_date).filled(:date?)
    optional(:energyprice_cents_per_kilowatt_hour).filled(:float?)
    optional(:baseprice_cents_per_month).filled(:int?)
  end

```

is there a ‘dryer’ way ?

---

<div class="post-metadata">

**Author:** ![art-solopov](https://yyz1.discourse-cdn.com/flex031/user_avatar/discourse.dry-rb.org/art-solopov/32/310_2.png) [@art-solopov](https://discourse.dry-rb.org/u/art-solopov)\
**Post date:** [June 23, 2018, 12:19pm UTC](https://discourse.dry-rb.org/t/reusing-schema-by-switch-required-to-optionsl/265/2 "2018-06-23T12:19:13Z")

</div>

I’d like to know an answer to this question too. I’d like to reuse the code between an Update schema and a Create schema but make all the fields in the Update schema optional.

P. S. The best I managed to do so far is this:

```ruby
class BaseSchema < Dry::Validation::Schema
  module Predicates
    include Dry::Logic::Predicates

    predicate(:name?) do |val|
      str?(val)
    end

    predicate(:code?) do |val|
      str?(val) & min_size?(3, val) & max_size?(10, val)
    end
  end

  configure do
    predicates(Predicates)
  end

  define! do
    required(:name) { name? }
    required(:code) { code? }
  end
end

class UpdateSchema < BaseSchema
  define! do
    optional(:name) { name? }
    optional(:code) { code? }
  end
end

```
