I came across an interesting problem in one of my ActiveRecord models (paraphrased, this isn’t the exact model):
The problem is I would set certainty to one of the accepted values, let’s say 'less', and the form would wind up throwing an error. I overrode the default error message just to retrieve the value and it turns out the value for certainty is 0.
The reason this was happening is because certainty is defined as a PostgreSQL
and these are the type detection methods in ActiveRecord:
The field_type in the above method calls is 'certainty.' The simplified_type in PostgreSQLColumn doesn’t match on any of the cases and it gets passed to the parent. In the parent, Column, 'certainty' matches against 'when /int/i' and returns integer as a type. Once the integer is set as the type, ActiveRecord does its thing and converts the attribute to an integer prior to a save. The validation then triggers on the changed value.
I couldn’t figure out where the variable actually gets type checked and changed to the correct type value. I tried modifying the column type directly in the model but that didn’t prevent the variable from being converted. My solution was to simply ALTER TYPE certainty RENAME TO certain. Postgre cascaded the changes and everything ended up being okay.