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
I get
Validation failed: a can only be whole number., a can only be between 1 and 999.
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?
Thanks
You can add an
:allow_nil => trueto yourvalidates_numericality_of.You can also use
greater_than_or_equal_toandless_than_or_equal_tooptions if you just want to use one validation: