在密码重置期间,对Devise模型中的某些成员进行跳过validation
我的用户(设计)模型还有姓名,城市,国家,电话会员。
在创建注册页面 – 我validates_presence_of city, nation, phone, name, email, :on => :create
_存在validates_presence_of city, nation, phone, name, email, :on => :create
在编辑注册页面中 – 我validates_presence_of city, nation, phone, name, :on => :update
现在,当我在forgot_password_page上设置一个新密码时,它会询问Devise::PasswordsController#update
是否存在城市,国家,电话,姓名
我该如何处理选择性validation?
我猜它应该是这样的,
validates_presence_of city, nation, phone, name, :on => :update, :if => :not_recovering_password def not_recovering_password # what goes here end
我遇到了类似的问题,因为创建用户时并不是所有的字段都是必需的。 检查其他字段的存在on: :update
使用validationon: :update
。
所以这就是我解决的问题:
validates :birthdate, presence: true, on: :update, unless: Proc.new{|u| u.encrypted_password_changed? }
方法encrypted_password_changed?
是Devise Recoverable中使用的那个。
我遇到了这个问题寻找类似问题的答案,所以希望其他人认为这很有用。 在我的情况下,我正在处理遗留数据,这些数据缺少以前不需要但之后需要的字段的信息。 以下是我完成上述代码所做的工作:
validates_presence_of city, nation, phone, name, :on => :update, :if => :not_recovering_password def not_recovering_password password_confirmation.nil? end
基本上,它使用password_confirmation字段的缺席/存在来知道用户是否正在尝试更改/重置其密码。 如果没有填写,则不会更改它(因此,运行您的validation)。 如果它已填满,则它们正在更改/重置,因此,您希望跳过validation。
得到了José的回答 – https://github.com/plataformatec/devise/issues/1623
在Devise模型中,您可以覆盖reset_password!
并使用您自己的validation。 例如:
def reset_password!(new_password, new_password_confirmation) self.password = new_password self.password_confirmation = new_password_confirmation validates_presence_of :password validates_confirmation_of :password validates_length_of :password, within: Devise.password_length, allow_blank: true if errors.empty? clear_reset_password_token after_password_reset save(validate: false) end end