简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM