“ password_digest不能为空”和“ password不能为空”错误

时间:2019-12-27 07:19:22

标签: ruby-on-rails ruby postman rails-api ruby-on-rails-6

我正尝试通过邮递员创建用户,如屏幕截图所示,但出现错误:

enter image description here

这是使用--api选项创建的Rails应用。

user.rb

class User < ApplicationRecord
  validates :email, uniqueness: true
  validates_format_of :email, with: /@/
  validates :password_digest, presence: true

  has_secure_password
end

users_controller.rb

class Api::V1::UsersController < ApplicationController
    # GET /users/1
    def show
      render json: User.find(params[:id])
    end
    # POST /users
    def create
        @user = User.new(user_params)

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

    private

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

routes.rb

Rails.application.routes.draw do
  namespace :api, defaults: { format: :json } do
    namespace :v1 do
      resources :users, only: [:show, :create]
    end
  end
end

1 个答案:

答案 0 :(得分:2)

您的user_params方法要求将属性嵌套在user哈希中。将响应更改为:

{
  "user": {
    "email": "...",
    "password": "..."
  }
}

由于has_secure_password内置了验证并在内部确保存在密码,因此不需要validates :password_digest, presence: true行。