Laura Diane Hamilton

Technical Product Manager at Groupon


Rails: Force empty string to NULL in the database

If you're importing data from an external source and you end up getting a bunch of empty strings back, it's not a good idea to save empty strings in the database.

Here is why that is bad:

  1. You will confuse users who are trying to query the database. They will use phrases like 'where middle_name is null', but records with empty strings will not be returned by the query.
  2. You will probably end up with some null records that are created a different way. This will be confusing and tough to manage.

Fortunately, it's quite easy to make rails save those pesky empty strings as null values.

First, install the nilify_blanks gem: gem "nilify_blanks"

Then, for any models for which you want to convert empty strings to null values, check and convert all fields: class Post < ActiveRecord::Base   nilify_blanks end is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to