【发布时间】:2022-01-23 12:08:06
【问题描述】:
当我尝试创建一个帐户时,我收到一个错误,即请求失败,状态码为 422。当我使用 params.require 时会发生这种情况,但是当我只使用 params.permit 时它可以工作但仍然显示
不允许的参数
我已经检查过了,参数正在通过。我遇到的另一个问题是我得到了
密码不能为空
尝试使用params.require 创建帐户时。我正在使用has_secure_password 和bcrypt。
我拥有的唯一验证:
validates :username, presence: true, confirmation: {case_sensitive: false}, uniqueness: true, length: {in: 6..30}
validates :password, presence: true, confirmation: true
这是我的代码:
class UsersController < ApplicationController
skip_before_action :authorize, only: [:create]
def create
# byebug
user = User.create!(user_params)
session[:user_id] = user.id
render json: user, status: :created
end
def show
render json: @current_user, include: :animes
end
def update
user = User.find_by(id: params[:id])
if user.update(user_params)
render json: user, status: :ok
else
render json: user.errors, status: :unprocessable_entity
end
end
private
def user_params
params.require(:user).permit(:username, :password, :password_confirmation, :bio, :avatar, :email)
end
end
这是我在前端的表单的所有代码:
<Form.Group className="mb-2">
<Form.Label className="signup-form-headers">Username</Form.Label>
<Form.Control type="username" value={formData.username} name="username" onChange={handleInput} placeholder="Enter Username" />
</Form.Group>
<Form.Group className="mb-2" controlId="formBasicPassword">
<Form.Label className="signup-form-headers">Password</Form.Label>
<Form.Control type="password" value={formData.password} name="password" onChange={handleInput} placeholder="Password" autoComplete="on"/>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPasswordConfirmation">
<Form.Label className="signup-form-headers">Confirm Password</Form.Label>
<Form.Control type="password" value={formData.password_confirmation} name="password_confirmation" onChange={handleInput} placeholder="Confirm your password" autoComplete="on"/>
</Form.Group>
const [formData, setFormData] = useState({
username:"",
password:"",
password_confirmation:""
})
const [errors, setErrors] = useState([])
const history = useHistory()
function handleInput(e) {
setFormData({...formData, [e.target.name]: e.target.value})
}
async function handleSubmit(e) {
e.preventDefault()
try {
if (formData.password != formData.password_confirmation) {
setErrors(["Password and Password confirmation do not match"])
return
}
await axios.post('/signup', formData)
setUserIsLoggedIn(true)
setFormData({
username:"",
password:"",
password_confirmation:""
})
history.push("/")
} catch (error) {
console.log("error:", error)
console.log("error data:", error.response.data.errors)
setErrors(error.response.data.errors)
}
}
是什么阻止了帐户创建?
【问题讨论】:
-
看起来您的表单没有正确嵌套。
username、password和password_confirmation也应该嵌套在user哈希中。你的表单是什么样子的? -
显示 html.erb 文件
标签: ruby-on-rails ruby