问题
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