Is there a shortcut for checking a field only when it is present in Rails 3?

I do it myself:

validates_numericality_of :mileage,:if => Proc.new {|car| car.mileage.present? }

Sometimes the mileage field may not be sent, but when it is, I want it to be checked. I have no problem with Proc inside my code, but this is the code that I duplicate for all other optional fields. Is there a shortcut, for example :if => present?? I am using Rails 3.0.5.

+3
source share
2 answers

Check out : allow_nil

: allow_nil - if set to true, this check is skipped if the attribute is nil (default is false).

According to the API docs, empty strings are converted to nils before validation, so this should work anyway.

+8
source

before_validation nil, :allow_nil validates_numericality_of:

before_validation :clean_up_milage # This would replace '' with nil
validates_numericality_of :milage, :allow_nil => true
+1

All Articles