如何在某些情况下仍然允许属性为零的同时验证数值和包含? [英] How to validate numericality and inclusion while still allowing attribute to be nil in some cases?
问题描述
在 Rails 应用程序中,我在模型上有几个整数属性.
In a Rails app I have several integer attributes on a model.
用户应该能够创建记录并将这些属性留空.
A user should be able to create a record and leave these attributes blank.
或者,如果用户为这些属性输入值,则应验证它们的数量和在一定范围内.
Or, if the user enters values for these attributes, they should be validated for numericality and within a certain range.
在模型中我有这样的东西
In the model I have something like this
validates_presence_of :name
validates_numericality_of :a, :only_integer => true, :message => "can only be whole number."
validates_inclusion_of :a, :in => 1..999, :message => "can only be between 1 and 999."
如果我现在用最少的必需属性进行测试:
If I now test with the minimum required attributes to save:
factory :model do
sequence(:name) { |n| "model#{n}" }
end
it "should save with minium attributes" do
@model = FactoryGirl.build(:model)
@model.save.should == false
end
我明白了
Validation failed: a can only be whole number., a can only be between 1 and 999.
如何仅在为 :a
指定值时验证数字和包含性,同时在某些情况下仍允许 :a
为零?
How can I validate numericality and inclusion only if a value is given for :a
, while still allowing :a
to be nil in some cases?
谢谢
推荐答案
您可以添加 :allow_nil =>对您的
.validates_numericality_of
为真
You can add an :allow_nil => true
to your validates_numericality_of
.
validates_numericality_of :a, :only_integer => true, :allow_nil => true,
:message => "can only be whole number."
如果您只想使用一种验证,也可以使用 greater_than_or_equal_to
和 less_than_or_equal_to
选项:
You can also use greater_than_or_equal_to
and less_than_or_equal_to
options if you just want to use one validation:
validates_numericality_of :a, :only_integer => true, :allow_nil => true,
:greater_than_or_equal_to => 1,
:less_than_or_equal_to => 999,
:message => "can only be whole number between 1 and 999."
这篇关于如何在某些情况下仍然允许属性为零的同时验证数值和包含?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!