There is a gem that can do that for you automatically for every attributes existing in your model :
Add this to your Gemfile and run bundle install :
gem 'nilly_vanilly'
This gem will convert any empty string into a NIL value to be store into your DB.
====== UPDATE =====
I just tried this Gem and it is not working. I reported it, and the developper said there was an incompatibility with postgreSQL. He is patching the gem. In the time being, I end up with creating my own library.
Just create the file lib/my_model_tools.rb containing the following lines :
module MyModelTools
private
def blank_string_attributes_to_nil
self.attributes.each do |attr_name, attr_value|
self.send("#{attr_name}=", nil) if attr_value.kind_of?(String) && attr_value == ''
end
end
end
Then you have to add these lines into each of your app/models/* files :
require Rails.root.to_s + '/lib/my_model_tools.rb'
class MyExampleModel < ActiveRecord::Base
include MyModelTools
before_validation :blank_string_attributes_to_nil
...
end
This will convert any empty string attributes into a NIL value to be store into your DB (for the models where you copy the lines above).
So you won't have to assign each attribute by hand to NIL when they are empty string.