我想使用 postman、rails 5 和 devise gem 创建一个用户帐户。我向设计用户模型添加了一个用户名字段,并确认它工作正常。但是,当我向 Rails API 发送发布请求时,它没有按预期创建用户。以下是整个过程的过程:
我将此 JSON post 请求发送到 URL:http://0.0.0.0:3000/users/
{
"username": "username",
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4d232c20280d28352c203d2128632e2220" rel="noreferrer noopener nofollow">[email protected]</a>",
"password": "password",
"password_confirmation": "password"
}
发送此请求后,我收到以下响应:
{
"status": "ERROR",
"message": "Could not create new user account",
"data": {
"email": [
"can't be blank"
],
"password": [
"can't be blank"
]
}
}
我创建了另一个继承自 Devise::RegistrationController 的注册 Controller 。这是:
1 module Api
2 module V1
3 class RegistrationsController < Devise::RegistrationsController
4
5 before_action :configure_permitted_parameters
6 respond_to :json
7 def new
8 user = User.new(user_params)
9 end
10
11 def create
12 user = User.create(username: params[:username],
13 email: params[:email],
14 password: params[:password],
15 password_confirmation: params[:password_confirmation])
16
17 if user.save
18 render json: {status: "SUCCESS", message: "Created new user account", data: user }, status: :ok
19 else
20 render json: {status: "ERROR",
21 message: "Could not create new user account",
22 data: user.errors},
23 status: :unprocessable_entity
24
25 end
26 end
27
28 private
29
30 def user_params
31 params.require(:user).permit(:username, :email, :password, :password_confirmation)
32 end
33
34 protected
35
36 def configure_permitted_parameters
37 devise_parameter_sanitizer.permit(:sign_up, keys: [:username])
38 end
39
40 end
41 end
42 end
知道为什么我会收到此回复以及如何解决它吗?我从 params
哈希中获取电子邮件和密码,并将其传递到创建函数中。我不知道为什么我收到的回复显示它是空的
最佳答案
您应该格式化嵌套在“user”下的参数,例如:
{
"user": {
"username": "username",
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="026c636f6742677a636f726e672c616d6f" rel="noreferrer noopener nofollow">[email protected]</a>",
"password": "password",
"password_confirmation": "password"
}
}
如 this answer 上所示
关于ruby-on-rails - 使用 json 发送 post 请求来设计注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50473652/