验证以保证唯一性,但忽略空值? [英] Validation to ensure uniqueness of but ignoring empty values?

查看:252
本文介绍了验证以保证唯一性,但忽略空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的模型现场验证:

I have the following model field validation:

validates_uniqueness_of :acronym, :scope => [:group_id], :case_sensitive => false

现在的问题是,这一领域是可选的,和一个空/空值被返回作为已经采取的首字母缩写。我只是想验证的缩写,是独特的,如果提供了一个值..有没有一种方法来更新这个验证,只需要的地方,如果有实际价值..不是零/空的?

The problem is that this field is optional, and a empty/nil value is returning as being an acronym already taken. I only want to validate that an acronym is unique if a value was provided.. Is there a way to update this validation to only take place if there is an actual value.. not nil/empty?

感谢

推荐答案

是的,有一些可以传递给验证为可选字段两个可能的选择::allow_blank :allow_nil ,这将跳过验证上空白字段,分别。如果你改变你的验证,下面,你应该得到你想要的行为:

Yes, there are two possible options that you can pass to validations for optional fields: :allow_blank or :allow_nil, which will skip the validations on blank and nil fields, respectively. If you change your validation to the following, you should get the behaviour you want:

validates_uniqueness_of :acronym, :allow_blank => true, :scope => [:group_id], :case_sensitive => false

这篇关于验证以保证唯一性,但忽略空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆