【问题标题】:#<ActionController::ParameterMissing: param is missing or the value is empty: user>#<ActionController::ParameterMissing:参数丢失或值为空:用户>
【发布时间】:2018-12-19 06:21:22
【问题描述】:

看了很多答案,但仍然找不到解决方案。 我一直在尝试成功响应对以下控制器的 POST 请求,

def create
@user = User.new(user_params)

if @user.save
  render json: @user, status: :created, location: @user
else
  render json: @user.errors, status: :unprocessable_entity
end


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

虽然我在请求中发送了所有提到的参数,但我仍然面临错误。

"status": 400,
"error": "Bad Request",
"exception": "#<ActionController::ParameterMissing: param is missing or the value is empty: user>"

我使用的是rails版本5.2.1

【问题讨论】:

  • 您能分享在发布请求中发送的视图代码或数据吗?
  • { "user": { "name": "pranesh", "email": "pranesh@gmail.com", "phone":"987654321","password": "hello" } } 这是 POST 请求中发送的数据

标签: ruby-on-rails-5 strong-parameters actioncontroller


【解决方案1】:

如果您查看日志,您的 post 请求中传输的数据是什么样的?

当您收到此类错误时,通常是因为您发送的数据是这样的:

{ first_name: 'John', last_name: 'Doe', ...}

当服务器希望您将其嵌套到 user 对象中时(因此 require(:user) in your strong_params:

{ user: { first_name: 'John', ... } }

【讨论】:

  • { "user": { "name": "pranesh", "email": "pranesh@gmail.com", "phone":"987654321","password": "hello" } } 这是 POST 请求中发送的数据
【解决方案2】:

这对我有用。 我在 params 方法中只创建了一个散列,而不是嵌套散列。 我的 user_params 方法是:-

定义用户参数 params.permit(:name, :email, :phone, :password) 结束

或者您可以使用您的方法,但您的参数在用户哈希中传递,如下所示。

{用户:{名称:“bittu”,电子邮件:“abc@yopmail.com”,phome:123456,密码:“123456”}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 2021-11-20
    • 1970-01-01
    • 2019-08-22
    相关资源
    最近更新 更多