You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么Devise允许不传password_confirmation创建User?如何强制要求传入?

解决方法

Devise 自带的 :validatable 模块默认规则为:仅当请求传入 password_confirmation 参数时,才会校验该值与 password 是否一致,未传入时默认跳过确认校验,所以会出现你遇到的现象。按照以下两步配置即可强制要求创建用户时必须携带该参数:

1. 给 User 模型添加 presence 校验

修改 user.rb 文件,新增 password_confirmation 的必填校验:

class User < ApplicationRecord
  devise :database_authenticatable,
         :jwt_authenticatable,
         :registerable,
         :validatable,
         jwt_revocation_strategy: JwtDenylist

  # 新增以下校验,on: :create 表示仅创建用户时强制要求,更新密码时也需要的话可以去掉该限制
  validates :password_confirmation, presence: true, on: :create
end

2. 确认自定义注册控制器的参数白名单

因为你重写了 Devise 的注册控制器,需要确保 password_confirmation 已经加入到注册接口的允许参数列表中,否则传入的参数会被 Rails 强参数过滤,依然触发必填校验报错。
你自定义的 app/controllers/api/v1/users/registrations_controller.rb 中需要包含以下配置:

class Api::V1::Users::RegistrationsController < Devise::RegistrationsController
  before_action :configure_sign_up_params, only: [:create]

  protected

  def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up, keys: [:password_confirmation])
  end
end

配置完成后即可实现预期效果:

  • 未传入 password_confirmation:创建失败,返回字段不能为空的错误提示
  • 传入的 password_confirmation 与 password 不一致:创建失败,返回字段不匹配的错误提示
  • 传入的 password_confirmation 与 password 一致:用户创建成功

内容的提问来源于stack exchange,提问作者tobiasz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 12:45:09