sensae
sensae

Reputation: 493

Custom Rails Validation throwing undefined method error

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?

Upvotes: 2

Views: 1366

Answers (2)

Jakob S
Jakob S

Reputation: 20125

All validators are run, regardless of the order they're defined in. That way the error array is filled with all the validation errors, allowing the end user to fix all the errors and not just one at a time.

So yes, you need to check if a value exists for the field, and that the value can be compared to a number. For example, uou probably also need to take into account that the value can be anything other than a number - a blank String would be a likely value - which would also cause an error.

But it's all academic, because as Stephen pointed out, just use validates_numericality_of :field, ::greater_than_or_equal_to => 0

Upvotes: 0

Stephen
Stephen

Reputation: 3432

Rails already has this:

http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_numericality_of

Use :greater_than => 0

Upvotes: 2

Related Questions