簡體   English   中英

在Rails中創建新用戶時,我不斷收到“密碼不能為空”錯誤

[英]I keep getting “password can't be blank” error when creating a new user in Rails

我正在用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": "jim@anywhere.com",
    "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。 參數將是用戶。 只需嘗試使用用戶參數即可。

{“用戶”:{“名稱”:“測試”}}

我知道這幾乎不能直接回答您的問題,但我認為這會有所幫助。 使用這個叫做byebug的寶石。 基本上,先安裝它,然后在用戶保存在控制器中之前放置byebug 當它執行代碼時,它將掛起服務器,直到您在服務器選項卡中鍵入繼續。 在鍵入繼續之前,您可以像使用rails控制台一樣使用服務器選項卡,並調試參數的當前狀態等等。 希望這可以幫助您調試問題。

感謝Rajkumar的回答。 最初,我的前端發送的是這樣的JSON對象:

{
  "name": "Someone",
  "password": "a_password",
  ...
}

但是,Rails期望這樣的程序被包裝在user哈希中,如下所示:

{
  "user": {
    "name": "Somebody",
    "password": "a_password",
    ...
  }
}

謝謝大家的幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM