<?xml version="1.0" encoding="UTF-8"?>
<code>
  <code>require 'erb'
class ClientMigrator
  def self.create(fields)
    erb_migration = ERB.new &lt;&lt;-EOS
  class AddClients &lt; ActiveRecord::Migration
    def self.up
      create_table :clients do |t|
        &lt;% fields.each do |name, type| %&gt;t.column :&lt;%= name %&gt;, :&lt;%= type %&gt;
        &lt;% end %&gt;
      end
    end

    def self.down
      drop_table :clients
    end
  end
EOS
    File.open("db/migrate/003_add_clients.rb", "w+") do |f|
      f.puts erb_migration.result(binding)
    end
    `rake db:migrate`
  end
end

# Example call
ClientMigrator.create(:name =&gt; :string, :phone =&gt; :string)</code>
  <comment>How do you create a rails project if you don't know the schema in advance? ERB to the rescue!

Blogged background: http://www.danielharan.com/2007/10/12/rails-migration-hackery-with-erb/</comment>
  <created-at type="datetime">2007-10-12T04:27:08+00:00</created-at>
  <id type="integer">78</id>
  <language>Ruby</language>
  <permalink>dynamic-migrations-for-rails</permalink>
  <refactors-count type="integer">1</refactors-count>
  <title>Dynamic migrations for rails</title>
  <trackback-url></trackback-url>
  <updated-at type="datetime">2007-10-12T04:30:57+00:00</updated-at>
  <user-id type="integer">3</user-id>
  <refactors type="array">
    <refactor>
      <code>
class ClientMigrator
  def self.create(fields = {})
    fields.each do |field, type|
      ActiveRecord::Base.connection.add_column(:clients, type)
    end
  end
end

ClientMigrator.create(:name =&gt; :string, :phone =&gt; :string)</code>
      <code-id type="integer">78</code-id>
      <comment>Hrrrm, this is a very confusing bit of code, because I believe the concept shown here is flawed from the start.... BUUUUUT

I wouldn't use migrations for this at all if I was going to do something as dirty as "dynamically" adding fields to a db with Rails. 

This is assuming you just created a `clients` database with whatever default fields.</comment>
      <created-at type="datetime">2007-10-12T16:27:41+00:00</created-at>
      <id type="integer">399</id>
      <language>Ruby</language>
      <rating type="integer">5</rating>
      <ratings-count type="integer">2</ratings-count>
      <title>On Dynamic migrations for rails</title>
      <user-id type="integer">5</user-id>
      <user-name>Hampton</user-name>
      <user-website nil="true"></user-website>
    </refactor>
  </refactors>
</code>
