title: How to validate numericality and inclusion while still allowing attribute to be nil in some cases?
body: <p>In a Rails app I have several integer attributes on a model. </p>
  
  <p>A user should be able to create a record and leave these attributes blank.</p>
  
  <p>Or, if the user enters values for these attributes, they should be validated for numericality and within a certain range.</p>
  
  <p>In the model I have something like this</p>
  
  <pre><code>validates_presence_of :name    
  validates_numericality_of :a, :only_integer =&gt; true, :message =&gt; "can only be whole number."
  validates_inclusion_of :a, :in =&gt; 1..999, :message =&gt; "can only be between 1 and 999."
  </code></pre>
  
  <p>If I now test with the minimum required attributes to save:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>I get </p>
  
  <pre><code>Validation failed: a can only be whole number., a can only be between 1 and 999.
  </code></pre>
  
  <p>How can I validate numericality and inclusion only if a value is given for <code>:a</code>, while still allowing <code>:a</code> to be nil in some cases?</p>
  
  <p>Thanks</p>