Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

ruby on rails - Skip email validation in Devise

In Devise Validatable module contains validates_uniqueness_of :email, :allow_blank => true, :if => :email_changed? How to disable this validator?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Per Devise's own documentation on the Validatable module...

Validatable creates all needed validations for a user email and password. It's optional, given you may want to create the validations by yourself. Automatically validate if the email is present, unique and its format is valid. Also tests presence of password, confirmation and length.

Bolding my emphasis.

You should disable the Validatable module and roll your own validations.

devise :database_authenticatable, :registerable, :rememberable,
       :trackable, :timeoutable, :confirmable, :recoverable, :lockable
       # :validatable <-- this one needs to go

Review the contents of lib/devise/models/validatable.rb and pull the relevant sections into your own User class. For the current 3.2.x version line, it should look something like this...

class User < ActiveRecord::Base

  # From Devise module Validatable
  validates_presence_of   :email, if: :email_required?
  validates_uniqueness_of :email, allow_blank: true, if: :email_changed?
  validates_format_of     :email, with: email_regexp, allow_blank: true, if: :email_changed?

  validates_presence_of     :password, if: :password_required?
  validates_confirmation_of :password, if: :password_required?
  validates_length_of       :password, within: password_length, allow_blank: true

  # [ ... ] The rest of your model stuff

  protected

  # From Devise module Validatable
  def password_required?
    !persisted? || !password.nil? || !password_confirmation.nil?
  end

  # From Devise module Validatable
  def email_required?
    true
  end

end

Then make whatever changes are necessary.

A real world scenario: I use the Paranoia gem on a number of projects, which won't work with this module. So I remove it and customize the email uniqueness check to read as...

validates_uniqueness_of :email, scope: :deleted_at

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...