设计通过电子邮件或手机号码注册

San*_*yal 4 ruby-on-rails devise

我可以在我的应用程序中注册一个同时获取电子邮件地址和手机号码的用户。但我真正想要的是使用电子邮件或移动设备作为主要身份验证密钥来注册用户。因此,如果用户提供电子邮件地址,则必须将其保存在数据库的电子邮件字段中,如果用户提供手机号码,则必须将其保存在数据库的手机字段中。

而且我想覆盖移动用户的确认方法,并想发送带有激活密钥的消息,并在应用程序中插入密钥以激活注册。我认为这并不难,但我不知道从哪里开始。请建议我完成这项任务的有利方式。

Har*_*yay 6

是的,您可以通过较小的设置轻松完成。

像这样

修改你的 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
Run Code Online (Sandbox Code Playgroud)
Create a login virtual attribute in the User model
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)

修改 config/initializers/devise.rb 以具有:

config.authentication_keys = [ :login ]
Run Code Online (Sandbox Code Playgroud)

您可以参考此链接以获取更多参考。

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