ruby-on-rails - rails - 设计强参数总是不允许注册
问题描述
我想在设计中为我的用户模型注册允许:full_name参数,并且我总是得到Unpermitted parameter: :full_name作为对 Users::RegistrationsController#create 操作的响应
我已经尝试了几种方法,接下来我将向您展示:
1. 应用程序控制器(选项 1)
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
case params[:action]
when 'create'
devise_parameter_sanitizer.permit(:sign_up, keys: %i[full_name])
when 'update'
...
end
end
end
结果 => 不允许的参数::full_name
2.注册控制器(选项2)
class Users::RegistrationsController < Devise::RegistrationsController
before_action :configure_sign_up_params, only: :create
protected
def configure_sign_up_params
params.require(:user).permit(%i[full_name])
end
end
结果 => 不允许的参数::full_name
3.注册控制器(选项3)
class 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: %i[full_name ])
end
end
结果 => 不允许的参数::full_name
在我的宝石文件中:
gem 'devise', '~> 4.8'
在我的路线中:
devise_controllers = {
confirmations: 'users/confirmations',
registrations: 'users/registrations',
invitations: 'users/invitations',
}
devise_for :users, controllers: devise_controllers
我已经阅读了设计强大的参数,但老实说我不知道我做错了什么。
我还尝试在 Users::RegistrationsController#create 中调试发生了什么:
def create
super do
binding.pry
end
end
但它跳过了调试器断点......你知道发生了什么吗?
干杯!
编辑:
- 根据 JohnP 的建议,我只留下了 :full_name 用于 sign_up 的设计键参数消毒剂
- 我还删除了一个绕过我的调试断点的回调,现在我可以在创建操作中使用 pry 停止
解决方案
通常,您为特定控制器编写强参数,而不是在 ApplicationController 中,因为每个模型的允许条件会有所不同。使用时devise_parameter_sanitizer
,您只需要包含要添加的额外字段 - 这不是从头开始设置您的强参数,只需将键添加到默认设计列表。
因此,您应该会发现这就是您在 Users::RegistrationsController 中所需要的。
def configure_sign_up_params
devise_parameter_sanitizer.permit(:sign_up, keys: [:full_name])
end
(顺便说一句,确保您正确引用参数,如params[:user][:full_name]
。)
(哦,如果你想进行调试,我建议安装 byebug gem。你只需byebug
在你想要断点的地方添加一个额外的行。)
推荐阅读
- swift - 当模型类具有空键值时,集合视图不显示项目
- c - C 中的 HTTPS 发布请求
- javascript - 为旧浏览器迁移 JS 中的高级代码的正确方法
- html - CSS - 卡片上的倾斜背景
- ios - 为什么我的表格视图单元类实例不在我的 Swift 代码中运行它的初始化程序?
- java - 从 Spring App (docker-compose) 在 Mongodb 连接上获取“异常打开套接字”
- java - 如何简化此代码以按降序对用户输入进行排序
- docker - 尝试在 unix:///var/run/docker.sock 连接到 Docker 守护程序套接字时获得权限被拒绝:发布
- python - 以块的形式写入 xarray 多索引数据
- json - 如何在jq中将更新与函数结果结合起来?