Devise在API请求中说“密码不能为空”-Rails API

时间:2018-11-06 14:02:31

标签: ruby-on-rails api

我正在尝试使用Rails API用Devise创建一个新用户。但是,当您执行URL请求时,它会显示“密码不能为空”,而在Rails控制台上,它可以正常工作。以下是有关控制器和请求的一些信息。我在做什么错了?

控制器:

class Api::ClientsController < ApplicationController
    skip_before_action :verify_authenticity_token
    def index
        render json: Client.all
    end
    def show
        client = Client.find(params[:id])
        render json: client
    end
    def create
        client = Client.new(client_params)
        if client.save!
            head 200
        else
            head 500
        end
    end
    private
    def client_params
        params.require("client").permit(:name, :email, :password, :password_confirmation)
    end
end

卷曲请求:

curl -i -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"name":"oi", "email":"oi2@gmail.com","password":"123456", "password_confirmation":"123456"}' http://localhost:3000/api/clients

服务器响应:

  Processing by Api::ClientsController#create as JSON
  Parameters: {"name"=>"oi", "email"=>"oi2@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "client"=>{"name"=>"oi", "email"=>"oi2@gmail.com"}}
   (0.1ms)  begin transaction
  ↳ app/controllers/api/clients_controller.rb:12
  Client Exists (0.3ms)  SELECT  1 AS one FROM "clients" WHERE "clients"."email" = ? LIMIT ?  [["email", "oi2@gmail.com"], ["LIMIT", 1]]
  ↳ app/controllers/api/clients_controller.rb:12
   (0.1ms)  rollback transaction
  ↳ app/controllers/api/clients_controller.rb:12
Completed 422 Unprocessable Entity in 7ms (ActiveRecord: 0.4ms)
ActiveRecord::RecordInvalid (Validation failed: Password can't be blank):
app/controllers/api/clients_controller.rb:12:in `create'

1 个答案:

答案 0 :(得分:1)

您的CURL请求似乎不正确。

curl -i -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"name":"oi", "email":"oi2@gmail.com","password":"123456", "password_confirmation":"123456"}' http://localhost:3000/api/clients

这不会按预期将客户端属性放在client下。尝试以下方法:

curl -i -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"client":{"name":"oi", "email":"oi2@gmail.com","password":"123456", "password_confirmation":"123456"}}' http://localhost:3000/api/clients