Rails dry-validation passed when params missing and rise an error when it's present

509 views Asked by At

In my Rails 7 app I want to use dry-validation gem to validate incoming JSONs inside create method of my MandateController. Basically based on that JSON request:

  "sdd_setup_request": {
    "return_url": "https://example.com/return",
    "data": {
        (...)
    }
  }
}

I'm trying to validate it using that validator class:

  params do
    required(:sdd_setup_request).schema do
      required(:return_url).value(:string)
      required(:data).hash do
       (...)
      end
    end
  end
end

But still gets an error of sdd_setup_request is missing, when I change it to optional inside the validator class it will be passed. But then when I want to test if the other validations work and remove return_url form the JSON file I should get an error of missing return_url but the validation will pass instead.

Nothing fancy inside of the controller class:

class MandatesController < BaseController
  def create
    result = SddRequestValidator.call(params)
    if result.success?
     (...)
    else
      render_error(result.errors.to_h, status: :bad_request)
    end
  end

What did I missed here?

[Edit]

# Gemfile.lock
dry-validation (1.10.0)

I've got also the initializers/dry_validator.rb:

require 'dry/validation'

Dry::Validation.load_extensions(:monads)

parent class ApplicationService is here:

class ApplicationService < Dry::Validation::Contract
  def self.call(*args)
    new.call(*args)
  end
end
1

There are 1 answers

0
Sanjay Prajapati On

I am not sure if this is an issue but if you are using the rails params method or if you are using strong parameters then call .to_h on it before passing params to validation.

For example if you have below method

def user_params
  params.require(:user).permit(:name, :email)
end

Pass above params like this: result = UserSchema::CreateParams.call(user_params.to_h)