Search code examples
ruby-on-railsrails-migrations

How can I make all tables contain certain columns in Rails 4?


Let's assume I'm going to create 10 tables and they have 4 columns in common. Is there an easy way to generate the migration without specifying all 4 columns in each of 10 table's migration file?


Solution

  • It's pretty easy to create your own migration helper. I'll create a simple one that adds created_by and updated_by columns with a migration helper called userstamps.

    Create an new initializer file config/initializers/userstamps.rb:

    module UserstampMigrationHelper
      def userstamps
        column :created_by, :integer
        column :updated_by, :integer
      end
    end
    
    ActiveRecord::ConnectionAdapters::TableDefinition.include(UserstampMigrationHelper)
    

    Now you can use it in a migration:

    class WidgetsMigration < ActiveRecord::Migration
      def change
        create_table :widgets do |t|
          t.string :name
          t.userstamps
        end
      end
    end