1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
require 'erb' class ClientMigrator def self.create(fields) erb_migration = ERB.new <<-EOS class AddClients < ActiveRecord::Migration def self.up create_table :clients do |t| <% fields.each do |name, type| %>t.column :<%= name %>, :<%= type %> <% end %> 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 => :string, :phone => :string)
Refactorings
No refactoring yet !
Hampton
October 12, 2007, October 12, 2007 16:27, permalink
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.
1 2 3 4 5 6 7 8 9 10
class ClientMigrator def self.create(fields = {}) fields.each do |field, type| ActiveRecord::Base.connection.add_column(:clients, type) end end end ClientMigrator.create(:name => :string, :phone => :string)
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/