I am building a simple registration page.
Here is my User model with it's validations, and associations:
class User < ApplicationRecord
has_secure_password
has_many :posts
has_many :comments
has_many :likes
validates :username, presence: true, uniqueness: true
validates :password, presence: true, length: { minimum: 6 }
end
Here is my User migration:
class CreateUsers < ActiveRecord::Migration[6.0]
def change
create_table :users do |t|
t.string :name
t.string :username
t.string :password_digest
t.integer :age
t.integer :years_in_the_labor
t.string :title
t.string :location
t.string :ministry
t.timestamps
end
end
end
Here is also my User controller create method:
def create
@user = User.new(name: params[:name], title: params[:title], username: params[:username], password: [:password])
if @user.valid?
@user.save
render json: { status: 200, user: @user }
else
render json: { status: 401, message: @user.errors.full_messages }
end
end
I am sending the params through fetch
, here's what the params are:
<ActionController::Parameters {"name"=>"Test Name User", "title"=>"Test Title User", "username"=>"test_username_user", "password"=>"password123", "controller"=>"users", "action"=>"create", "user"=>{"name"=>"Test Name User", "username"=>"test_username_user", "title"=>"Test Title User"}} permitted: false>
And I get this error:
message: ["Password is too short (minimum is 6 characters)"]
My password validation is not working, although I pass the correct amount of characters.
You're passing to User.new just [:password] instead of params[:password]
it is most often used to pass parameters only a private function like this:
private
def user_params
params.require(:user).permit(:name, :title, :username, :password)
end
And then in your create method:
@user = User.new(user_params)
Update
And instead of asking if the user is valid you can directly check if the user was saved
if @user.save
# your code for success
else
# your code for failure
end