I need to validate that a field is a positive value, and wrote a little methid in lib/validations.rb which does exactly that and added it to my model. However, now one of my rspec tests is failing complaining…
NoMethodError: undefined method ‘<‘ for nil:NilClass”
…when the value is undefined. I’ve also added validates_presence_of :price to my model, above my custom validates_positive_or_zero method.
I would think that validates_presence_of would be called first, and when the field is nil it wouldn’t run further validation. Do I have to change my validates_positive_or_zero method to check if the field exists to fix this? Can anyone give me some insight into what’s going on?
Rails already has this:
http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_numericality_of
Use :greater_than => 0