bwaydev
bwaydev

Reputation: 13

I keep getting "password can't be blank" error when creating a new user in Rails

I'm creating what I thought was a simple user auth in a Rails API. I have searched every answer I can find here, and I simply can't figure out what I'm doing wrong. No matter what, when I try to create a new user, I get the error "password can't be blank."

Here is my controller code:

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

My model, with validations:

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

A test JSON object that keeps getting rejected:

{
    "name": "Jim Nobody",
    "email": "jim@anywhere.com",
    "password": "abc12345",
    "password_confirmation": "abc12345"
}

The error I keep getting:

{
    "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"
    ]
}

I know there are other answers to this question, but I have combed them line by line, and I can't see what I'm doing wrong. All the fields are permitted and spelled correctly, as far as I can see.

I would so appreciate any help. Thank you!

Upvotes: 0

Views: 3287

Answers (3)

Rajkumar Ulaganadhan
Rajkumar Ulaganadhan

Reputation: 708

Hi check your params in controller. Currently you are passing only Params. The params will be users. Just try to use users params.

{ "users": { "name":"test" } }

Upvotes: 3

bwaydev
bwaydev

Reputation: 13

Thanks to Rajkumar for the answer. Originally, my front end was sending a JSON object that looked like this:

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

But Rails was expecting one that was wrapped inside a user hash like this:

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

Thanks, everyone for the help!

Upvotes: 1

Noah
Noah

Reputation: 570

I know this is hardly a direct answer to your question, but in my opinion, it will help. Use this gem called byebug. Basically, install it, then place byebug before the user save in the controller. When it executed the code, it will hang the server until you type continue in the server tab. Until you type continue, you can use the server tab just like a rails console and debug the current state of the params and more. Hopefully this helps you debug your issue.

Upvotes: 0

Related Questions