这会做。它并不完美,因为它不会复制表选项或索引。如果您确实设置了任何表选项,则必须手动将它们添加到此迁移中。
要复制索引,您必须制定一个 SQL 查询来选择它们,然后将它们处理成新的 add_index 指令。这有点超出我的认知。但这适用于复制结构。
class CopyTableSchema < ActiveRecord::Migration
def self.up
create_table :new_models do |t|
Model.columns.each do |column|
next if column.name == "id" # already created by create_table
t.send(column.type.to_sym, column.name.to_sym, :null => column.null,
:limit => column.limit, :default => column.default, :scale => column.scale,
:precision => column.precision)
end
end
# copy data
Model.all.each do |m|
NewModel.create m.attributes
end
end
def self.down
drop_table :new_models
end
end