Hello guys I am working on a login page with a javascript/html/css frontend and a rails backend. So when clicking on a signup button in my front end I am making a POST request to the create action in rails and passing a username, password and password confirmation. I put a byebug in the create action to look at the params and it looks like this
#<ActionController::Parameters {"username"=>"ray",
"password"=>"1234",
"password_confirmation"=>"1234",
"controller"=>"users",
"action"=>"create",
"user"=>#<ActionController::Parameters {"username"=>"ray"} permitted: false>} permitted: false>
I try to save the user but for some reason I can't save the user because the password and password_confirmation are not being returned from my user_params method. This is what my UsersController looks like.
class UsersController < ApplicationController
def create
user = User.new(user_params)
if user.save
session[:user_id] = user.id
render json: {
status: 200,
user: user
}
else
render json: {
status: 401,
message: "Failure!"
}
end
end
private
def user_params
byebug
params.require(:user).permit(:username, :password, :password_confirmation)
end
end
I guess what I don't understand is why only the username is being plugged in.
CodePudding user response:
Your incoming parameters look like this:
{
"username" => "ray",
"password" => "1234",
"password_confirmation" => "1234",
"user" => { "username" => "ray" }
}
but the require
in your user_params
:
params.require(:user).permit(:username, :password, :password_confirmation)
is looking at the user
in those parameters and then the permit
looks for the username
, password
, ... within user
. So user_params
is looking for input like this:
{
"user" => {
"username" => "ray",
"password" => "1234",
"password_confirmation" => "1234"
}
}
So either fix your front end to send the data properly nested with "user"
as above or fix user_params
to look for everything at the top level:
params.permit(:username, :password, :password_confirmation)