当 Rails 中不存在该属性时,如何停止其他验证以进行验证?
我目前正在做的事情如下:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
:allow_nil
标志 < code>validates 可能会让人感兴趣。像这样的东西应该有效:The
:allow_nil
flag forvalidates
might be of interest. Something like this should work: