在Rails应用程序中,我有一些模型上的整数属性.
或者,如果用户输入这些属性的值,则它们应该在数值范围内并在一定范围内进行验证.
在模型中,我有这样的东西
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."
如果我现在用最小要求的属性进行测试以保存:
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在某些情况下为零,如何验证数值和包含?
谢谢
解决方法
你可以添加一个:allow_nil =>真实的你的validates_numericality_of.
validates_numericality_of :a,:allow_nil => true,:message => "can only be whole number."
如果您只想使用一个验证,也可以使用greater_than_or_equal_to和less_than_or_equal_to选项:
validates_numericality_of :a,:greater_than_or_equal_to => 1,:less_than_or_equal_to => 999,:message => "can only be whole number between 1 and 999."