Devise sign up either by email or by mobile number

前端 未结 2 1905
忘掉有多难
忘掉有多难 2021-02-06 14:53

I can register a user getting both email address and mobile number in my application. But what I really want is to register user using either email or mobile as a primary authen

2条回答
  •  眼角桃花
    2021-02-06 15:48

    Yes, you can do easily with minor setting.

    like this

    Modify your application_controller.rb

    class ApplicationController < ActionController::Base
      before_action :configure_permitted_parameters, if: :devise_controller?
    
      protected
    
      def configure_permitted_parameters
        added_attrs = [:mobile_no, :email, :password, :password_confirmation, :remember_me]
        devise_parameter_sanitizer.permit :sign_up, keys: added_attrs
        devise_parameter_sanitizer.permit :account_update, keys: added_attrs
      end
    end
    
    Create a login virtual attribute in the User model
    
    Add login as an attr_accessor:
    
      # Virtual attribute for authenticating by either username or email
      # This is in addition to a real persisted field like 'username'
      attr_accessor :login
    or, if you will use this variable somewhere else in the code:
    
      def login=(login)
        @login = login
      end
    
      def login
        @login || self.mobile_no || self.email
      end
    

    Modify config/initializers/devise.rb to have:

    config.authentication_keys = [ :login ]
    

    You can refer this link for more reference.

    https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign-in-using-their-username-or-email-address

提交回复
热议问题