Peter Marklund

Peter Marklund's Home


Rails Tip: Inserting NULL to the Database Instead of Empty Strings

The value NULL in a relational database represents the absence of a value. Empty text fields and text areas in HTML forms on the other hand get submitted in Rails as empty strings. This means you can easily end up with empty strings in the database where you would expect NULL values. I came up with the following workaround for our ActiveRecord models:

5 comment(s)


Henrik N said 2010-12-03 07:04:

Peter, thanks! I think "nonblank?" would be a better name than "presence" as Ruby has the analogous "nonzero?" built in, but this is the name that DHH prefers.

Peter Marklund said 2010-11-29 13:59:

Henrik, I like your approach much better than mine. Makes more sense to override directly on write. Also, why not do it for all types. Didn't know about the presence method. Exactly what we need in this case. Not quite clear from the name what it does. I guess nullify_if_blank would be more informative, although not quite as pretty... Thanks! Peter

Henrik N said 2010-11-27 10:12:

I've done similar things by overriding write_attribute. Simplistic example:

Marc said 2010-11-26 14:46:

Interesting, we always do the opposite and disallow NULL in varchar or text columns and then we use an empty string as default for this columns.