Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate numericality and inclusion while still allowing attribute to be nil in some cases?

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

like image 423
Andy Harvey Avatar asked May 22 '12 11:05

Andy Harvey


People also ask

Can we save an object in DB if its validations do not pass?

If any validations fail, the object will be marked as invalid and Active Record will not perform the INSERT or UPDATE operation. This helps to avoid storing an invalid object in the database. You can choose to have specific validations run when an object is created, saved, or updated.

How do I validate in Ruby on Rails?

This helper validates the attributes' values by testing whether they match a given regular expression, which is specified using the :with option. Alternatively, you can require that the specified attribute does not match the regular expression by using the :without option. The default error message is "is invalid".

What is validate in rails?

In Rails, validations are used in order to ensure valid data is passed into the database. Validations can be used, for example, to make sure a user inputs their name into a name field or a username is unique.


1 Answers

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."

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."
like image 182
Shadwell Avatar answered Oct 21 '22 20:10

Shadwell