How might you clone a database table via Rails migration? How might you clone a database table via Rails migration? ruby-on-rails ruby-on-rails

How might you clone a database table via Rails migration?


Try doing it with pure SQL. This will do what you want:

CREATE TABLE new_tbl LIKE orig_tbl;


In Rails 4 & PostgreSQL, create a new migration and insert:

ActiveRecord::Base.connection.execute("CREATE TABLE clone_table_name AS SELECT * FROM source_table_name;")

This will create the clone with the exact structure of the original table, and populate the new table with old values.

More info: http://www.postgresql.org/docs/9.0/static/sql-createtableas.html


This will do. It's not perfect, because it won't copy table options or indices. If you do have any table options set, you will have to add them to this migration manually.

To copy indices you'll have to formulate a SQL query to select them, and then process them into new add_index directives. That's a little beyond my knowledge. But this works for copying the structure.

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  endend