[英]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. 我们假设我要创建10个表,它们共有4列。 Is there an easy way to generate the migration without specifying all 4 columns in each of 10 table's migration file? 是否有一种简单的方法来生成迁移,而无需在10个表的每个迁移文件中指定所有4列?
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
. 我将创建一个简单的,添加created_by
和updated_by
列,并使用名为userstamps
的迁移帮助userstamps
。
Create an new initializer file config/initializers/userstamps.rb
: 创建一个新的初始化文件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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.