通过干验证对Rails控制器进行参数验证

时间:2018-11-13 09:15:46

标签: ruby-on-rails validation

我第一次尝试使用干燥验证宝石。

我想为多模型(用户,地址,公司)创建表单

我决定使用干燥验证器,但无法验证表单。我收到验证程序错误“:user => [“必须为哈希”]“

如何使其工作?

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

在创建操作中打印参数输出:

<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>

1 个答案:

答案 0 :(得分:0)

dry-validation(和dry-schema)不接受ActionController::Parameters,您应该将其转换为哈希。

尝试params.to_unsafe_hashparams.permit(...).to_h