["must be a hash"]" 如何使它-6ren">
gpt4 book ai didi

ruby-on-rails - 通过干验证进行 Rails Controller 参数验证

转载 作者:行者123 更新时间:2023-12-04 13:02:18 25 4
gpt4 key购买 nike

我第一次尝试使用干验证 gem。

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

我决定使用干验证器,但我无法验证表单。我收到验证器错误 ":user=>["must be a hash"]"

如何使它工作?

应用程序/ 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

应用程序/模型/user.rb
class User < ApplicationRecord
has_one :company
has_one :address, as: :addressable
accepts_nested_attributes_for :company, :address
end

应用程序/验证器/用户验证器
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>

最佳答案

干验证(和干模式)不接受 ActionController::Parameters ,您应该将其转换为哈希。

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

关于ruby-on-rails - 通过干验证进行 Rails Controller 参数验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53277535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com