Wojtek Kostański
Wojtek Kostański

Reputation: 311

Rails controller params validation by dry-validation

First time I'am trying using dry validation gem.

I want to create a form for multi-models (User, Address, Company)

I decided to use a dry validator but I can't validate the form. I receive validator error ":user=>["must be a hash"]"

How to make it work?

app/controller/users_controller.rb

class UsersController < ApplicationController
  def new
    @user = User.new
    @user.address = Address.new
    @user.company = Company.new
    @user.company.address = Address.new
  end

  def create
    @user = User.new
    validation = UserValidator::UserSchema.call(params)
    if validation.success?
      @user.attributes = validation.output[:user]
      @user.save
      redirect_to new_user_path, notice: 'Form send!'
    else
      redirect_to new_user_path, warning: "#{validation.errors}"
    end
 end
end

app/models/user.rb

class User < ApplicationRecord
  has_one :company
  has_one :address, as: :addressable
  accepts_nested_attributes_for :company, :address
end

app/validators/user_validator

class UserValidator
  UserSchema = Dry::Validation.Params do
    required(:user).schema do
      required('first_name').filled
    end
  end
end

print params output in create action:

<ActionController::Parameters {"utf8"=>"✓","authenticity_token"=>"Dszr0k90aklK1NC4uGcemAl+yFa9ppMDo/gCLJt2wC1WjTgLC+NFebRqm6iqtVTnQzRgd7v0icntxETbxJ7v9g==", "user"=>{"first_name"=>"Test", "last_name"=>"asdasdasdasd", "email_address"=>"sadasdasd", "date_of_birth"=>"sdasda", "phone_number"=>"", "address_attributes"=>{"street"=>"dadadadsdad", "city"=>"asdasdad", "zip_code"=>"dasd", "country"=>"adsa"}, "company_attributes"=>{"name"=>"", "address_attributes"=>{"street"=>"", "city"=>"", "zip_code"=>"", "country"=>""}}}, "commit"=>"Submit", "controller"=>"users", "action"=>"create"} permitted: false>

Upvotes: 4

Views: 2476

Answers (1)

NDan
NDan

Reputation: 2162

dry-validation (and dry-schema) does not accept ActionController::Parameters, you should convert it to a hash.

Try params.to_unsafe_hash or params.permit(...).to_h

Upvotes: 4

Related Questions