Search code examples
ruby-on-railsruby-on-rails-3migrationdatabase-migrationrails-migrations

Rails Migrations: How to split one table into two tables?


I have a database with the following schema:

[ Region ] 1 --- * [ District ] 1 --- * [ Location ]

I would like to split the middle table into two tables as follows:

[ Region ] 1 --- * [ District ] 1 --- * [ Area ] 1 --- * [ Location ]

...leaving some fields (and their values) in the original District table while transferring other columns (and their values) into the newly-created Area table.

Is there a standard/clean way to do this in a rails migration (preferably without the use of raw SQL)?


Solution

  • Well you could do this in 2 steps:

    First step

    Write a migration that creates the Area table and its columns. In this migration write some Ruby code to populate the table with data from District.

    Second step

    Write a migration that changes the District table, for example one that drops unwanted columns from District.

    At this point running the migrations should get you what you want without having to use SQL.

    Hope it helps ! : )