1

my postgres database table was setup with

t.integer :time_employed

I had validations like so

validates :time_employed, numericality: true, allow_blank: true

and I also tried

validates_numericality_of :time_employed, allow_blank: true

But neither of them gave me the result I was looking for. I did some testing in the console and it seemed that the field was always being set to 0 or nil. If I input a string it was being set to 0.

I changed the database field to

t.string :time_employed

and now everything works like it should. It's not a huge problem, but I was hoping to keep the data correctly described by the schema.

I don't know much about databases yet, so this threw me for a loop. Can anyone explain what is happening here?

EDIT:

The problem was that it would allow blank entries, but it wouldn't throw an error if I input non numeric values. Anything would be validated as good, just not saved to the DB. After changing to t.string and no changes to the validations, it worked fine.

I also tried allow_nil: true but it had the same effect.

2 Answers 2

1

Replace this

validates_numericality_of :time_employed, allow_blank: true

by

validates_numericality_of :time_employed, allow_nil: true

allow_blank is not present in api docs this may be one of the reason.

Sign up to request clarification or add additional context in comments.

1 Comment

The question was edited. I tried allow_nil also but it had the same outcome. The weird thing was, with t.integer it wouldn't error with non numeric values. After I changed to t.string and no change to the model, everything worked fine.
0

because your time_employed column is type-casted before validation.

validates_numericality_of :time_employed_before_type_cast, allow_blank: true

should work.

Comments

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.