我正在创建我认为是Rails API中的简单用户身份验证。我已经搜索了我在这里找到的每个答案,而我根本无法弄清楚我做错了什么。无论如何,当我尝试创建一个新用户时,我收到错误“密码不能为空”。
这是我的控制器代码:
class UsersController < ApplicationController
def create
user = User.new(user_params)
if user.save
render json: {user: user}, status: 201
else
render json: {errors: user.errors.full_messages}
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
end
我的模型,带有验证:
class User < ApplicationRecord
validates :name, presence: true, length: {maximum: 50}
validates :email, presence: true, length: {maximum: 255}, uniqueness: true
has_secure_password
validates :password, presence: {on: :create}, confirmation: {case_sensitive: true}, length: {minimum: 8}
validates :password_confirmation, presence: true
end
一个持续被拒绝的测试JSON对象:
{
"name": "Jim Nobody",
"email": "[email protected]",
"password": "abc12345",
"password_confirmation": "abc12345"
}
我一直得到的错误:
{
"errors": [
"Password can't be blank",
"Password can't be blank",
"Password is too short (minimum is 8 characters)",
"Password confirmation can't be blank"
]
}
我知道这个问题还有其他答案,但我已逐行梳理它们,我看不出我做错了什么。据我所知,所有字段都是允许的,拼写正确。
我非常感谢任何帮助。谢谢!
嗨检查控制器中的参数。目前你只通过Params。参数将是用户。只是尝试使用用户参数。
{“users”:{“name”:“test”}}
我知道这不是你问题的直接答案,但在我看来,这会有所帮助。使用这个名为byebug的宝石。基本上,安装它,然后在用户保存在控制器之前放置byebug
。执行代码时,它将挂起服务器,直到您在服务器选项卡中键入continue。在键入continue之前,您可以像使用rails控制台一样使用服务器选项卡,并调试params的当前状态等。希望这可以帮助您调试您的问题。
感谢Rajkumar的回答。最初,我的前端发送了一个看起来像这样的JSON对象:
{
"name": "Someone",
"password": "a_password",
...
}
但Rails期待一个包含在user
哈希中的一个像这样:
{
"user": {
"name": "Somebody",
"password": "a_password",
...
}
}
谢谢大家的帮助!