Peter Marklund

Peter Marklund's Home

Thu November 25, 2010
Programming

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:

Comments

Marc said over 3 years ago:

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.

--------------------------------------------------------------------------------

Henrik N said over 3 years ago:

I've done similar things by overriding write_attribute. Simplistic example: https://gist.github.com/717764

--------------------------------------------------------------------------------

Peter Marklund said over 3 years ago:

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 over 3 years ago:

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.

--------------------------------------------------------------------------------