How might you clone a database table via Rails migration?

Teflon Ted picture Teflon Ted · Oct 9, 2009 · Viewed 11.6k times · Source

I want a migration to create a clone of an existing table by just suffixing the name, including all the indexes from the original table.

So there's a "snapshots" table and I want to create "snapshots_temp" as an exact copy of the table (not the data, just the table schema, but including the indexes).

I could just copy and paste the block out of the schema.rb file and manually rename it.

But I'm not sure by the time this migration is applied if the definition from schema.rb will still be accurate. Another developer might have changed the table and I don't want to have to update my migration script.

So how might I get the schema of the table at runtime? Essentially, how does 'rake schema:dump' reverse engineer the table so I can do the same in my migration? (but changing the table name).

Answer

zenazn picture zenazn · Oct 12, 2009

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

CREATE TABLE new_tbl LIKE orig_tbl;