dry-rails how to use contract validation

804 views Asked by At

after adding the gem dry-rails to my rails application, I have defined a contract:

module Users
  module Contracts
    class New < ApplicationContract
      params do
        required(:todo).schema do
          required(:title).filled(:string)
          required(:items).array(:hash) do
            required(:name).filled(:string)
          end
        end
      end
    end
  end
end

But I don't know how to make this contract work. Let's say I have a controller named UsersController:

module Api
  module V1
    class UsersController < ApplicationController
      before_action :set_user

      private
      def set_user
        @user = User.find(params[:user_id])
      end
    end
  end
end

how can I make this controller use the contract New to get validation run?

1

There are 1 answers

0
tmaier On

When I understand the example at https://github.com/dry-rb/dry-rails/blob/v0.5.0/spec/dummy/app/controllers/users_controller.rb correctly, you need to call safe_params instead of params

Specifically safe_params.success? or safe_params[:id]

Besides this, at the "HTTP boundary", dry recommends to use dry-schema instead of dry-validation.

The contract you mentioned is more for an operator