Adding extra registration fields with Devise

前端 未结 8 581
情话喂你
情话喂你 2020-12-01 06:57

I am trying to add some extra fields to registrations#new. Since I only want extra data and do not need different functionality, I don\'t see why I need to override controll

相关标签:
8条回答
  • 2020-12-01 07:29

    I've had similar situation (just fields were different).

    Here's the way official documentation can offer: Just add this to your ApplicationController. And change "username" to whatever you need, and add some more if you need.

    before_action :configure_permitted_parameters, if: :devise_controller?
    
      protected
    
      def configure_permitted_parameters
        devise_parameter_sanitizer.for(:sign_up) << :username
      end
    

    My Applications Controller looks like that:

    class ApplicationController < ActionController::Base
      # Prevent CSRF attacks by raising an exception.
      # For APIs, you may want to use :null_session instead.
      protect_from_forgery with: :exception
    
      before_action :configure_permitted_parameters, if: :devise_controller?
    
      protected
    
        def configure_permitted_parameters
          devise_parameter_sanitizer.for(:sign_up) << :public_name
        end
    end
    

    More details here: https://github.com/plataformatec/devise ("Strong Parameters")

    0 讨论(0)
  • 2020-12-01 07:32

    OK, so what I did was just override the Devise registration controller, update routes.rb as per the devise docs to reflect this, copied and pasted the Devise code for registrations#create as is, and change the getting params part to use my own strong parameters method, and that was that.

    class RegistrationsController < Devise::RegistrationsController
    
      def create
        build_resource(registration_params)
    
        if resource.save
          if resource.active_for_authentication?
            set_flash_message :notice, :signed_up if is_navigational_format?
            sign_up(resource_name, resource)
            respond_with resource, :location => after_sign_up_path_for(resource)
          else
            set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
            respond_with resource, :location => after_sign_up_path_for(resource)
          end
        else
          clean_up_passwords
          respond_with resource
        end
      end  
    
      private
    
      def registration_params
        params.require(:user).permit(:email, :title_id, :first_name, :last_name, 
          :province_id, :password, :password_confirmation)
      end
    
    end
    
    0 讨论(0)
提交回复
热议问题