How do I force all tables to contain specific columns in Rails 4?

Let's say I am going to create 10 tables and they have 4 columns. Is there an easy way to generate a migration without specifying all 4 columns in each of the 10 table migration files?

+3


source to share


1 answer


It is very easy to create your own migration assistant. I will create a simple one that adds columns created_by

and updated_by

using the migration helper userstamps

.

Create a 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 your migration:

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

      

+3


source







All Articles