[英]Validate Rails attribute presence but allow empty string
I want to validate a string attribute is not nil, but allow empty strings. 我想验证字符串属性不是nil,但允许空字符串。
As in: 如:
validates name: not_nil, allow_empty: true
你也可以这样做:
validates :name, exclusion: { in: [nil] }
To allow an empty string, but reject nil in an active record validation callback, use a conditional proc to conditionally require the presence of the attribute if it's not nil. 要允许空字符串,但在活动记录验证回调中拒绝nil,请使用条件proc来有条件地要求存在属性(如果它不是nil)。
So the code looks like: 所以代码看起来像:
validates :name, presence: true, if: proc { name.nil? }
But you probably want to allow null. 但是你可能想要允许null。 Then don't validate.
然后不要验证。 Still check for presence?
还在检查存在吗? in code for nil or empty string.
代码为nil或空字符串。
另外
validates :name, presence: true, allow_blank: true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.