On before_type_cast, numeric columns and blank


I noticed that when you set a numeric column’s attribute to an empty string, the attribute before_type_cast doesn’t reflect that value but returns nil instead:

item = Item.new

e.cents = " "

This brings the following remarks:

  • if someone wants to provide a different validation for " " and nil (like I had to do twice recently), they can’t rely on before_type_cast for that. They’ll have to work-around it by using a custom accessor for instance

  • there’s what seems to be a hint of this data massage of the before_type_cast in the documentation

  • the behavior from the user point of view differs from ActiveModel validates_numericality_of which will reject a blank value, if I’m not mistaken

  • more generally, one can then wonder if there are other data massaging of before_type_cast attributes happening on other types or contexts (I didn’t find any so far though)

Can someone with more knowledge of the internals and the history of ActiveRecord shed some light on this?

Is consistency here desirable and worth pursuing?

Alternatively, should this be documented alongside with before_type_cast in the documentation?

– Thibaut