【问题标题】:Ruby on Rails - Failed to create new user: Validation failedRuby on Rails - 无法创建新用户:验证失败
【发布时间】:2021-07-13 17:43:01
【问题描述】:

在使用邮递员创建新用户时,我收到以下错误:

新建用户失败:验证失败:名字不能为空,Email不能为空,Email无效;参数:{:email=>nil, :first_name=>nil, :last_name=>nil, :plan=>"Basic", :role=>"requester_readonly", :phone_number=>nil, :ip=>nil, : company_name=>nil, :product_id=>2, :user_reference_id=>nil, :handle=>nil}

邮递员错误:

{
    "error": [
        "First name can't be blank",
        "Email can't be blank",
        "Email is invalid"
    ],
    "status": 400
}

我将以下值传递给邮递员中的参数:

{
    "email": "customer@yahoo.com",
    "firstName": "Demo",
    "lastName": "Customer",
    "password": "Password_0",
    "phoneNumber": "0123456789",
    "ip": "10.10.2.125",
    "company": "xyz"
}

这是用户注册的功能:

def register
        product_id = $product_id
        if params[:plan]
        @plan = AppCommon::Plan.where(name: params[:plan], product_id: product_id).first
      end
      @plan = @plan || AppCommon::Plan.find_default(product_id)

          form_params = {email: params[:email], first_name: params[:firstName], last_name: params[:lastName], password: params[:password], plan: @plan.name, role: 'requester_readonly', phone_number: params[:phoneNumber], ip: params[:ip], company_name: params[:company], product_id: product_id, user_reference_id: params[:referenceId]}
          service = Web::UserCreater.new(form_params)
        result = service.perform
        @user = service.user
        if result.success?
          render json: {status: 200, authentication_token: @user.authentication_token}
        else
          error_response(@user.errors.full_messages.to_a)
        end
      end

【问题讨论】:

  • 你能发布日志文件中的实际参数吗?

标签: ruby-on-rails validation postman


【解决方案1】:

可能是 ruby​​ on rails 控制器将参数包装在名称 https://api.rubyonrails.org/classes/ActionController/ParamsWrapper.html

您可以通过在控制器顶部设置wrap_parameters false 来关闭它但我不建议这样做!

您可能可以打印/记录整个参数以查看它们的外观并可能允许它们

form_params 拉到它自己的方法中需要参数包装器然后允许你需要的东西


def form_params
  params.require(:user).permit(:email, :first_name, :last_name, :password, :phone_number, :ip, :company_name, :user_reference_id)
end

然后在您的方法中获取这些参数,然后合并默认值:

user_creater_attributes = form_params.merge(product_id: product_id, plan: @plan.name, role: 'requester_readonly')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-09
    • 2021-09-23
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 2018-10-24
    相关资源
    最近更新 更多