"password_digest can't be blank" 和 "password can't be blank" 错误

"password_digest can't be blank" and "password can't be blank" errors

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

这是使用 --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

您的 user_params 方法需要嵌套在 user 散列中的属性。将响应更改为:

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

顺便说一句,不需要 validates :password_digest, presence: true 行,因为 has_secure_password 内置了验证功能并在内部确保密码存在。