Is there a shortcut for validating a field only when it's present, in Rails 3?
I find myself doing this:
validat开发者_StackOverflow社区es_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 validated. I have no problem in having the Proc inside my code, but it's code which I'm kind of duplicating for all the other optional fields. Is there a shortcut like :if => present?
?
I'm using Rails 3.0.5.
Check out :allow_nil
:allow_nil - If set to true, skips this validation 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 in either case.
You could use a before_validation
hook to convert empty strings to nil
and then use the :allow_nil
option to validates_numericality_of
:
before_validation :clean_up_milage # This would replace '' with nil
validates_numericality_of :milage, :allow_nil => true
精彩评论