Create new model - add custom defaults to migration?

I am new to Ruby and Rails, have been messing about with migrations
mostly, was trying to create a migration file that would automattically
add certain columns and triggers to each table in the database, made
some progress with that but now rethinking my approach

when creating a new model/migration file, is it possible to get the
generator to add in default values; in my case I would like a few
columns such as created_on, modified_on, and some triggers to update
these values

so given a model Project, the following migration file is generated via
ruby script/generate model Project

class CreateProjects < ActiveRecord::Migration
  def self.up
    create_table :projects do |t|
    end
  end

  def self.down
    drop_table :projects
  end
end

but is it possible to have the generated file automatically load in
additional code? i.e.

class CreateProjects < ActiveRecord::Migration
  def self.up
    create_table :projects do |t|
      t.column :created_on, :datetime
      t.column :modified_on, :datetime
    end

    sql = 'CREATE TRIGGER projects_before_insert BEFORE INSERT ON
projects FOR EACH ROW SET NEW.created_on = NOW(); '
    execute(sql)

  end

  def self.down
    drop_table :projects
  end
end

Thanks in advance for any help or pointers

  • J

ok - after further Google searches came across this great site
‘Railscasts’
‘How to Make a Generator’ - #58 How to Make a Generator - RailsCasts

armed with a better understanding of how a generator works
I took a look at the model_generator.rb and /templates/migration.rb code

well a quick hack of the /templates/migration.rb code and I am on my way
BUT - this just feels down right dirty hacking this template directly;
but it is very effective

on windows XP with Ruby in installed at C:\Ruby
the path to this file is
C:\ruby\lib\ruby\gems\1.8\gems\rails-1.2.3\lib\rails_generator\generators\components\model\templates

the hacked version - created_on, modified_on columns and triggers

(mysql)
class <%= migration_name %> < ActiveRecord::Migration
def self.up
create_table :<%= table_name %> do |t|
<% for attribute in attributes -%>
t.column :<%= attribute.name %>, :<%= attribute.type %>
<% end -%>
t.column :created_on, :datetime
t.column :modified_on, :datetime
end

sql = 'CREATE TRIGGER <%= table_name %>_before_insert BEFORE INSERT 

ON <%= table_name %> FOR EACH ROW SET NEW.created_on = NOW(),
NEW.modified_on = NOW(); ’
execute(sql)

sql = 'CREATE TRIGGER <%= table_name %>_before_update BEFORE UPDATE 

ON <%= table_name %> FOR EACH ROW SET NEW.modified_on = NOW(); ’
execute(sql)
end

def self.down
drop_table :<%= table_name %>
end
end