问题
I use devise and devise-token-auth. I have User model with following content
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:login]
include DeviseTokenAuth::Concerns::User
validates_uniqueness_of :login
validates_presence_of :full_name
protected
def email_required?
puts "email_required called"
false
end
end
but devise email validation is still working
2.3.0 :003 > user = User.new(login: "hello", password: "11111111", password_confirmation: "11111111", full_name: "hello world")
=> #<User id: nil, provider: "email", uid: "", email: nil, full_name: "hello world", login: "hello", created_at: nil, updated_at: nil>
2.3.0 :004 > user.valid?
email_required? called #<===== my method is called!
(3.7ms) SELECT COUNT(*) FROM "users" WHERE "users"."provider" = $1 AND "users"."email" IS NULL [["provider", "email"]]
User Exists (1.0ms) SELECT 1 AS one FROM "users" WHERE "users"."login" = $1 LIMIT $2 [["login", "hello"], ["LIMIT", 1]]
=> false
2.3.0 :005 > user.errors
=> #<ActiveModel::Errors:0x000000028e2338 @messages={:email=>[...]}, @details={:email=>[{:error=>:blank}]}>
Why this? Thanks
回答1:
Your validations do not override the Devise validations, they just extend them. If you really want to remove the Devise validations, you can remove the :validatable module. But you will lose all the nifty validations (e.g. on the password) as well.
Or maybe try to do this first: (I didn't test this)
:authentication_keys => {email: false, login: true}
回答2:
If you just want to remove email validation. Edit User model to
devise :database_authenticatable, :registerable,:recoverable, :rememberable,
:trackable, :validatable, authentication_keys: [:password]
If you comletely want to remove validations. Remove validatable from User model.
回答3:
In my case I changed to username field. First I changed /config/initializers/devise.rb
--> config.authentication_keys = [:username]
And, as I use a legacy database, I have to change the primary key to username too and change the auth
method
def self.find_for_database_authentication(warden_conditions)
conditions = warden_conditions.dup
login = conditions.delete(:username)
where(["APP_NAME = '#{$app_name.downcase}' AND USERNAME = :value", { :value => login }]).first
end
来源:https://stackoverflow.com/questions/39725552/remove-devise-email-validation