1

I have a Rails 4 form which saves nested associations, using the simple_form gem, and Postgres as the DBMS. One of the models saved in the form has 2 numeric input fields. The validation rules for these fields are as follows:

validates_numericality_of :field1, greater_than: 0, only_integer: true, allow_nil: true
validates_numericality_of :field2, allow_nil: true

If I type strings like "ten" or "thirty-five" or "$$$$$" into these fields, no validation errors occur, the form data is saved, and these fields are given a nil value. If I put a negative or decimal value into field1, the expected validation error is presented.

While this is unlikely to cause a tremendous amount of problems with the administrators using this form, I can't seem to explain why this happens. All other validations for this form work as expected.

Why are these values converted to nil? Why do I not get a non-numeric validation error? Is this just an annoying quirk to the allow_nil property?

1 Answer 1

1

According to documentation, when you set only_integer: true, your value applying to the regular expression /\A[+\-]?\d+\Z/:

"123" =~ /\A[+\-]?\d+\Z/
#=> 0
"$$$$$" =~ /\A[+\-]?\d+\Z/
#=> nil
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply. This does not explain why the second field, which does not have only_integer, exhibits the same exact behavior. I can type "string" into the second field, and it will just get set to nil and save, instead of failing to save and displaying an error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.