Devise signing up user using email or mobile no

我的梦境 提交于 2019-12-13 22:23:03

问题


I followed this article to implement user registration either with email or username. https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign-in-using-their-username-or-email-address

User.rb


devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable, authentication_keys: [:login]
attr_accessor :login

def login=(login)
  @login = login
end

def login
 @login || self.contact_no || self.email
end

def self.find_for_database_authentication(warden_conditions)
 conditions = warden_conditions.dup
 if login = conditions.delete(:login)
  where(conditions.to_hash).where(["lower(contact_no) = :value OR lower(email) = :value", { :value => login.downcase }]).first
 elsif conditions.has_key?(:contact_no) || conditions.has_key?(:email)
  where(conditions.to_hash).first
 end
end

Devise.rb

config.authentication_keys = [ :login ]

But still getting error 'email can't be blank'. How can I fix this? Where am I getting wrong?


回答1:


You are following sign in article to solve issue with sign up. Simple you need to find from where this validation is coming in. Here is file .

Now to solve your issue, you need to override email_required? method in model where you are using devise. To check email required only when contact_no blank or whatever condition you want.

class User < ApplicationRecord

  def email_required?
    self.contact_no.blank? #If contact number blank then email required.
  end

end



回答2:


I have also required same functionality in my project.

You do not have to do that much code.

User.rb

def self.find_for_database_authentication(conditions={})
    find_by(contact_number: conditions[:email]) || find_by(email: conditions[:email])
end

sessions/new.html.erb

<%= f.text_field :email %>

Note: Your contact_number and email (field) in database should be uniq



来源:https://stackoverflow.com/questions/44593786/devise-signing-up-user-using-email-or-mobile-no

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!