brad
brad

Reputation: 9773

How do I use validates_numericality_of with a decimal field?

I have a table with a column (dose) that is defined as a decimal. When the user fills out the form field for this column I want to make sure they enter a valid number. I want to use validates_numericality_of :dose but this doesn't work. If the user enters a non-numeric value (e.g. 'horse') a value of 0 is saved to the database and the validation is passed. I would prefer an error was raised.

Is there a way of catching this earlier in the object lifecycle? At what point is active record converting the string to a 0?

Upvotes: 1

Views: 648

Answers (1)

Yardboy
Yardboy

Reputation: 2805

My expectation would be that you have another plugin or hook or something that's getting in the way and changing the value before validation.

To maybe get some more insight as to what the situation is, add a before_validation hook to the model and raise self.inspect to see what the object looks like right before the validations fire. Try to save an instance with text in the :dose attribute and see what it looks like.

Upvotes: 1

Related Questions