【问题标题】:Skip validation for some members in Devise model during password reset在密码重置期间跳过对设计模型中某些成员的验证
【发布时间】:2012-02-05 21:36:23
【问题描述】:

我的用户(设计)模型还有姓名、城市、国家、电话成员。

在创建注册页面-我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 中是否存在城市、国家、电话、姓名

如何处理选择性验证?

我猜应该是这样的,

validates_presence_of city, nation, phone, name, :on => :update, :if => :not_recovering_password

def not_recovering_password
  # what goes here
end

【问题讨论】:

标签: ruby-on-rails validation devise


【解决方案1】:

我遇到了类似的问题,因为创建我的用户时,并非所有字段都是必需的。使用验证检查其他字段是否存在on: :update

所以我就是这样解决的:

validates :birthdate, presence: true, on: :update, unless: Proc.new{|u| u.encrypted_password_changed? }

方法encrypted_password_changed?Devise Recoverable中使用的方法。

【讨论】:

  • 我可以知道这是如何工作的吗? encrypted_password_changed? 持有什么?
  • 太棒了!奇迹般有效! :)
  • 你可以说unless: :encrypted_password_changed?
  • Pietro @mmike 恐怕这只能解决问题的问题。但是,您应该知道,此解决方案还将跳过用户编辑配置文件表单中的验证。
  • @prajwaldp 这将在用户重置密码以及用户在用户编辑个人资料表单中更新密码时跳过验证。 column_changed?请参考docs
【解决方案2】:

我在寻找类似问题的答案时遇到了这个问题,因此希望其他人觉得这很有用。就我而言,我正在处理遗留数据,这些数据缺少以前不需要但后来被要求的字段的信息。这就是我所做的,基本上是为了完成上面的代码:


validates_presence_of city, nation, phone, name, :on => :update, :if => :not_recovering_password

def not_recovering_password
  password_confirmation.nil?
end

基本上,它使用 password_confirmation 字段的缺失/存在来了解用户是否正在尝试更改/重置其密码。如果它没有被填满,他们就不会改变它(因此,运行你的验证)。如果已填满,则它们正在更改/重置,因此您希望跳过验证。

【讨论】:

  • 我认为这是迄今为止最好的答案,它应该是标记的,你节省了我的时间谢谢:)
  • 你可以说if: "password_confirmation.nil?"
【解决方案3】:

在设计模型中,您可以覆盖 reset_password! 并使用您自己的验证。例如:

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

【讨论】:

    【解决方案4】:

    【讨论】:

    • 这甚至不是答案! “我的建议是简单地删除这些验证。”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多