Friday, March 09, 2007

table conformity in rails

I want all my tables to have certain characteristics. E.g. I want them all to be UTF-8, and all have a field called 'created_at'.

Instead of duplicating that code everywhere, here's what I'm doing:

class MyTables < ActiveRecord::Migration
  def self.create_table( table_name, options={}, &table_definition )
options[:options] = "" unless( options.has_key?( :options ) )
options[:options] += " DEFAULT CHARSET=UTF8 "
super( table_name, options ) do |t|
t.column :created_at, :timestamp, :null => false

class Foo < MyTables
# use this like a regular migration

So now every migration Foo that inherits from MyTables automatically gets some default goodness.

No comments: