且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Rails 4.0 中向设计添加新字段的不允许的参数

更新时间:2023-12-02 21:26:28

公认的解决方案已经足够好了,但我看到两个问题:1) 所有的控制器都会检查当前控制器是否是设计控制器 (if: :devise_controller?) 和 2) 我们需要在方法中写入所有可接受的参数 (...for(:sign_up) {|u| u.permit(:bio, :name)}),甚至是 :email:password 等等.

The accepted solution is good enough, but I see two problems: 1) All the controllers will check if the current controller is the devise controller (if: :devise_controller?) and 2) We need to write all the acceptable parameters in the method (...for(:sign_up) {|u| u.permit(:bio, :name)}), even the :email, :password and so on.

我认为更优雅的解决方案可能是:

I think that a more elegant solution could be:

# app/controllers/users/registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController
  before_filter :configure_permitted_parameters

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up).push(:name, :phone, :organization)
  end
end

# config/routes.rb
devise_for :users, :controllers => { :registrations => "users/registrations" }

注意:Rails 4.2+ 的更新

这个答案已经过时了:

  • Change "users" to "user" in the "users/registration" path for Rails 4.2.1 and Devise 3.4.1.
  • devise_parameter_sanitizer.permit() replaces devise_parameter_sanitizer.for() for Devise 4 (see Rails 5, Undefined method `for' for #<Devise on line devise_parameter_sanitizer.for)