Unpermitted Parameters adding new fields to Devise in rails 4.0

后端 未结 7 1670
灰色年华
灰色年华 2020-12-02 09:26

Very new to working with rails. I have implemented a basic login system using Devise. I am trying to add a couple of new fields (bio:string, name:string) into the sign_up pa

相关标签:
7条回答
  • 2020-12-02 09:59

    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" }
    

    NOTE: Updates for Rails 4.2+

    This answer is falling out of date:

    • 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)
    0 讨论(0)
提交回复
热议问题