How to create a migration file dynamically by meta programming in rails 4.0

If you want to add a migration file from lib file or somewhere from your ruby file and execute it, use the dynamic method which can create a class or method dynamically. The following code snippet is not complete. But gives a better idea to create migration file dynamically. Use a bit of metaprogramming.

 def create_columns(tb_with_cols)
    columns.each { |column| add_columns << "\tadd_column(':#{tb_name}', :#{column})\n" }

 def migration_file_content(tb_with_cols)
  class AddMissingColumnsToTable < ActiveRecord::Migration
     def change_table

 def write_content_to_file(path, content), 'w+') do |f|

Just call the method ‘migration_file_content’ in your code. Pass the parameter tb_with_cols as a Hash whose key is the table_name and value is the columns that should be added to that table like:

tb_with_cols = {:users => {:name => :string, :age => :integer, :address => :text} }

After that just call the method ‘write_content_to_file’ with your new migration file path and the content from our ‘migration_file_content’ method. 🙂

Author: Abhilash

Hey! This is Abhilash - A Ruby developer for years, specialised on web development. Right now working as a freelance Ruby Developer. I am also working on Angular, Sinatra and many other backend infra. Mainly working on Ruby On Rails platform since 2010. This blog is about Ruby, Ruby On Rails and other subjects that I had a chance to go through. You can contact me here: Abhilash AK

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s