[英]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”
I want to interrupt the default registration action in my rails application, changing email validation. 我想中断我的Rails应用程序中的默认注册操作,更改电子邮件验证。 All I need is to have email field unique ONLY if that user is already registered AND has role
'X'
. 我需要的是仅在该用户已经注册并且角色为
'X'
情况下,使电子邮件字段唯一。
I've tried the following but my application returns "Email has already been taken"
message: 我尝试了以下操作,但是我的应用程序返回
"Email has already been taken"
消息:
validation: 验证:
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
(I will be glad for any help) (我将很高兴为您提供帮助)
Assuming your model includes :validatable module of Devise, you can remove this module from your model and write your own validations as you desire. 假设模型包括Devise的:validatable模块,则可以从模型中删除此模块,并根据需要编写自己的验证。
In your model (say user.rb) your devise call contains :validatable like: 在您的模型中(例如user.rb),您的设计调用包含:validatable,例如:
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :confirmable, :trackable
Remove or comment :validatable from this call, then your own validations should work as you expected. 从此调用中删除或评论:validatable,然后您自己的验证应会按预期工作。
If you are using Rails 5, you need to override the below method in your User model 如果您使用的是Rails 5,则需要在用户模型中覆盖以下方法
def will_save_change_to_email?
if User.where(email: self.email, role: :X).exists?
return true
else
return false
end
end
when you return true
, devise will go ahead and apply the uniqueness
check and when you return false
devise will not check for uniqueness 当您返回
true
,devise将继续进行uniqueness
检查;当您返回false
devise将不检查唯一性
You will also need to remove the unique index
as by passing devise validation alone will not let you save the user 您还需要删除
unique index
因为仅通过设计验证就无法保存用户
def change
remove_index :users, :name => :index_users_on_email
end
Note: once you remove the index and create records with duplicate email ids, you will not be able to add the unique index back again at a later moment as creating unique index will fail 注意:删除索引并创建具有重复电子邮件ID的记录后,您将无法再重新添加唯一索引,因为创建唯一索引将会失败
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.