首页 > 解决方案 > 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

但它跳过了调试器断点......你知道发生了什么吗?

干杯!

编辑:

标签: ruby-on-railsdevise

解决方案


通常,您为特定控制器编写强参数,而不是在 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在你想要断点的地方添加一个额外的行。)


推荐阅读