ActiveRecord with NOT NULL columns

Using ActiveRecord with an unchangeable legacy database schema poses some interesting challenges. Most of the work is a new style (for me) of composing adapters to make non-Rails stuff work within Rails' conventions.

ActiveRecord uses the database's native NULL to indicate an unset attribute [Ruby's nil]. This becomes a problem when the column definition enforces NOT NULL on columns that you may or may not be setting values.

The following Ruby code allows a table with NOT NULL columns to "just work" with ActiveRecord by setting them to reasonable default values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class OldBacon < ActiveRecord::Base

  before_validation :prep_not_null_columns

  private
  
  def prep_not_null_columns
    self.class.columns.each do |c|
      unless c.null
        if read_attribute(c.name).nil?
          case c.type
          when :date
            new_value = Date.new
          else
            new_value = c.instance_values['original_default']
          end
          write_attribute(c.name, new_value)
        end
      end
    end
  end

end

Questionably defying good DBA practices? Perhaps. But sometimes you have to make the best with the hand your dealt.

About this Post

Author:
Mars
Published:
2007-07-27 22:45
Updated:
2007-07-27 22:48
Sections:
Ruby