当 Rails 中不存在该属性时,如何停止其他验证以进行验证?

发布于 2024-12-01 06:48:19 字数 737 浏览 0 评论 0原文

我目前正在做的事情如下:

validates :new_pass,
          :presence => {:if => :new_record?},
          :confirmation => {:if => :password_not_blank?},
          :length => {:within => 6...64, :if => :password_not_blank?}

def password_not_blank?
  !new_pass.blank?
end

但这不是干的,我敢打赌,如果属性不存在,有一种方法可以跳过验证。

另外,没有任何DSL方法来验证吗?我认为这比在散列中实现逻辑更干净...-

编辑,谢谢^^--

这就是我现在得到的:

validates :new_pass,
          :allow_blank => {:on => :update},
          :presence => {:on => :create},
          :confirmation => true,
          :length => {:within => 6...64}

只是为了记录,所以没有人担心(?),这是一个虚拟属性,实际密码使用 before_save 进行加密,检查 :new_pass 不为空。

What I'm curretly doing is the following:

validates :new_pass,
          :presence => {:if => :new_record?},
          :confirmation => {:if => :password_not_blank?},
          :length => {:within => 6...64, :if => :password_not_blank?}

def password_not_blank?
  !new_pass.blank?
end

But that is not DRY, I bet there is a way to skip the validations if the attribute is not present.

Also, there isn't any DSL method for validating? I think it would be cleaner than implementing logic inside hashes...

-- Edit, thanks ^^ --

This is what I got now:

validates :new_pass,
          :allow_blank => {:on => :update},
          :presence => {:on => :create},
          :confirmation => true,
          :length => {:within => 6...64}

And just for the record and so no one worries (?), this is a virtual attribute, the actual password is encrypted with a before_save, checking that :new_pass is not blank.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

白馒头 2024-12-08 06:48:19

:allow_nil 标志 < code>validates 可能会让人感兴趣。像这样的东西应该有效:

validates :new_pass,
          :allow_nil => true,
          :presence => {:if => :new_record?},
          :confirmation => {:if => :password_not_blank?},
          :length => {:within => 6...64, :if => :password_not_blank?}

The :allow_nil flag for validates might be of interest. Something like this should work:

validates :new_pass,
          :allow_nil => true,
          :presence => {:if => :new_record?},
          :confirmation => {:if => :password_not_blank?},
          :length => {:within => 6...64, :if => :password_not_blank?}
徒留西风 2024-12-08 06:48:19
validates :new_pass,:presence => true ,:if => :new_record?
validates :confirmation ,:length =>:within => 6...64, :if => :password_not_blank?
validates :new_pass,:presence => true ,:if => :new_record?
validates :confirmation ,:length =>:within => 6...64, :if => :password_not_blank?
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文