[英]Ruby on Rails: devise doesn't send email to the mailing address during sign_up
[英]Ruby On Rails Devise: How can I avoid email uniqueness validation during sign up and rewrite to check if it's unique only if has role “X”
我想中斷我的Rails應用程序中的默認注冊操作,更改電子郵件驗證。 我需要的是僅在該用戶已經注冊並且角色為'X'
情況下,使電子郵件字段唯一。
我嘗試了以下操作,但是我的應用程序返回"Email has already been taken"
消息:
驗證:
validates_uniqueness_of :email, {allow_blank: true, if: :already_exists_as_x?}
def already_exists_as_x?
User.where(email: self.email, role: :X).exists?
end
(我將很高興為您提供幫助)
假設模型包括Devise的:validatable模塊,則可以從模型中刪除此模塊,並根據需要編寫自己的驗證。
在您的模型中(例如user.rb),您的設計調用包含:validatable,例如:
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :confirmable, :trackable
從此調用中刪除或評論:validatable,然后您自己的驗證應會按預期工作。
如果您使用的是Rails 5,則需要在用戶模型中覆蓋以下方法
def will_save_change_to_email?
if User.where(email: self.email, role: :X).exists?
return true
else
return false
end
end
當您返回true
,devise將繼續進行uniqueness
檢查;當您返回false
devise將不檢查唯一性
您還需要刪除unique index
因為僅通過設計驗證就無法保存用戶
def change
remove_index :users, :name => :index_users_on_email
end
注意:刪除索引並創建具有重復電子郵件ID的記錄后,您將無法再重新添加唯一索引,因為創建唯一索引將會失敗
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.