Re: ActiveRecord uses confusing defaults

Andrew Stone
Fri, 08 Sep 2006 15:13:28 -0000

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...


--
Andrew Stone