Rails 3 基于动作验证规则 [英] Rails 3 validates rule based on action
问题描述
这似乎是一个简单的问题,但除了编写自定义验证器之外,我似乎找不到答案.我有这个验证器
This seems like a simple question but I can't seem to find an answer short of writing custom validators. I have this validator
validates :password, :presence => true, :confirmation => true, :length => { :minimum => 5}
应用了更多规则,例如一些用于复杂性的正则表达式,但这给出了要点.
there are more rules applied such as some regex for complexity, but this gives the gist.
问题是我只希望在创建时应用状态,其他所有内容都需要在创建和更新时进行.因为用户在更新他们的信息时可能没有更改密码.
The issue is that I only want presence applied on create, everything else needs to be on create and update. Because the user may not be changing a password when updating their information.
我尝试拆分规则
validates :password, :presence => true, :on => :create
validates :password, # The rest of the rules
这导致所有规则都被忽略以进行更新.有没有一种简单的方法可以只应用一条规则来创建,其余规则应用于所有内容?
This resulted in all rules being ignored for update. Is there a simple way to apply only one rule to create and the rest to everything?
推荐答案
您可以尝试将其保留在一行中,但应用 :on =>:create
到 :presence
检查:
You can try keeping it in one line, but applying :on => :create
to just the :presence
check:
validates :password, :presence => {:on => :create}, :confirmation => true, :length => { :minimum => 5}
但是,我不确定始终要求最小长度是否有意义,但并不总是要求存在——如果您使用空白密码更新现有记录,由于长度为 0,无论如何验证都会失败.
However, I'm not sure it makes sense to always require a minimum length, but not always require presence -- if you update an existing record with a blank password, it's going to fail validations anyway since the length is 0.
这篇关于Rails 3 基于动作验证规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!