Ruby on Rails
HowToCreateYourOwnColumnMethods

Rails 2.0.2

Used to seeing this in your generated migrations?


class CreateModel < ActiveRecord::Migration
  def self.up
    create_table :models do |t|

      ...
      t.timestamps
    end
...

timestamps is a method found in ActiveRecord::ConnectionAdapters::TableDefinition that adds two attributes, created_at and changed_at, to the table schema. If you have similar groups of attributes that are repeated in multiple tables then you can add your own methods to provide the effect of timestamps such as:


class CreateModel < ActiveRecord::Migration
  def self.up
    create_table :models do |t|

      ...
      t.audit_fields
    end
...

Files placed in config/initializers are always loaded whenever Rails is so that is where I would place the following file, but you can place it anywhere in the load path (lib is a good choice) and simply require it by name in the migration file itself.

The code for the audit_fields method above looks like this:


# Put this in config/initializers as active_record_addins.rb
module ActiveRecord
  module ConnectionAdapters
    class TableDefinition

      # Record access data                  
      def access_audit_fields
        column  :accessed_at,       :datetime,  :null => false
        column  :accessed_by,       :string,    :null => false
        column  :accessed_from,     :string,    :null => false
      end

      def all_audit_fields
        access_audit_fields
        data_audit_fields
      end

      def audit_fields
        data_audit_fields
      end

      # Record creation and modification data
      def data_audit_fields
        column  :changed_at,        :datetime,  :null => true
        column  :changed_by,        :string,    :null => false
        column  :created_at,        :datetime,  :null => false
        column  :created_by,        :string,    :null => false
      end

      # Record effective duration data
      def duration_fields
        column  :effective_from,    :datetime,  :null => false
        column  :superseded_after,  :datetime,  :null => true
      end

      # For those that forget the default setting!
      def lock_field
        column  :lock_version,      :integer,
                :null => false,     :default => 0
      end

    end
  end

end

In this scheme, the method audit_fields is an alias for data_audit_fields, the method that actually adds the columns. Method all_audit_fields demonstrates the means by which one may separate groups of special purpose columns and yet still aggregate them for convenience.