ActiveRecord uses confusing defaults

I’m not sure if this is what you are after (haven’t woken up), but I wrote a little plugin that would nil empty strings before saving the record. I’ve been using this for over a year without issue.

**Note This is an extract of my model_utils plugin so double check it for errors:

module ModelUtils def self.included(base) base.send :include, Stone::ModelUtils::InstanceMethods

  base.before_validation{|model|
    model.nil_empty_fields
  }
end


model InstanceMethods
  def nil_empty_fields
    self.attributes.each do |key, value|
      if not value.nil? and value.kind_of?(String)
        self[key] = nil if value.length == 0

      end
    end
  end

end #end instance methods

end

ActiveRecord::Base.send :include, ModelUtils

Hope this helps…

base.send :include, Stone::ModelUtils::InstanceMethods

should be

base.send :include, ModelUtils::InstanceMethods

Could you, just as a test, create this table a a corresponding empty model and tell me what value Submission.new.postcode returns?

CREATE TABLE submissions ( id int(11) NOT NULL auto_increment, email varchar(255) NOT NULL, fname varchar(255) NOT NULL, lname varchar(255) NOT NULL,

street varchar(255) NOT NULL, housenr int(11) NOT NULL, housenr_ext varchar(255) default NULL, postcode varchar(6) NOT NULL, city varchar(255) NOT NULL, shirt_type varchar(255) NOT NULL default ‘m’,

shirt_size varchar(255) NOT NULL default ‘l’, shirt_text text NOT NULL, processed_at datetime default NULL, approved_at datetime default NULL, created_at datetime NOT NULL, updated_at datetime NOT NULL,

PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

I will run this test tomorrow morning and let you know.