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

Rails 7中Devise出现Unpermitted parameters错误求助

解决Devise注册时Unpermitted parameters错误

问题背景

代码原本运行正常,新增数据库表后出现参数不允许的错误:Unpermitted parameters: :full_name, :password_confirmation,尝试多种方案无效,相关代码及错误信息如下:

控制器代码

class UsersController < ApplicationController
  before_action :configure_permitted_parameters, if: :devise_controller?

def create
  @user = User.new(user_params)
  if @user.save
    redirect_to root_path, notice: 'Sign up successful.'
  else
    render :new
  end
end

def index
  @users = User.all
end

protected

def configure_permitted_parameters
  devise_parameter_sanitizer.permit(:sign_up, keys: [:full_name, :password, 
  :password_confirmation])
end

错误信息

Unpermitted parameters: :full_name, :password_confirmation. Context: { controller: Devise::SessionsController, action: new, request: #ActionDispatch::Request:0x00007fc5b5ca5a58, params: {"authenticity_token"=>"[FILTERED]", "user"=>{"full_name"=>"shaker abu drais", "email"=>"shaker_abady@yahoo.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up", "controller"=>"devise/sessions", "action"=>"create"} }

问题分析

从错误上下文能看到两个核心问题:

  1. 注册请求被错误发送到了Devise::SessionsController#create(登录接口),而非注册接口,说明表单提交路径配置错误。
  2. 自定义UsersController中的参数白名单配置不会生效,因为Devise默认控制器不会继承你的UsersController,配置代码未被加载。

解决方案

1. 修正表单提交路径

确保注册表单的提交目标是正确的注册接口:

  • 若使用Devise默认路由,表单应提交到user_registration_path(对应路径/users)
  • 检查ERB表单代码,示例正确写法:
    <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
      # 表单字段内容
    <% end %>
    
    避免错误指向登录路径session_path。

2. 正确配置参数白名单

将参数白名单配置移至ApplicationController,确保所有Devise控制器都能加载该配置:

class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:full_name, :password, :password_confirmation])
  end
end

3.(可选)用自定义控制器处理注册

如果要通过自己的UsersController处理注册,需在config/routes.rb中覆盖Devise的注册路由:

devise_for :users, controllers: { registrations: 'users' }

同时修改UsersController的继承关系:

class UsersController < Devise::RegistrationsController
  before_action :configure_permitted_parameters, if: :devise_controller?

  # 保留自定义的create、index方法...

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:full_name, :password, :password_confirmation])
  end
end

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 14:06:55