williamcodes williamcodes - 25 days ago 4x
Ruby Question

How to fix database that has many tables without matching migrations with Rails

I'm helping out with a friend's rails app. They have a database that contains many tables which were added manually using SQL rather than with rails migrations. They've started adding migrations normally, but they need to get the two back in sync.

If we add the migrations now, they'll error because those tables/columns already exist. If we leave them out, people have to use db:schema:load to get up and running, and then run migrations one at a time by name to avoid errors. We'd like to avoid that and get back to a healthy state instead.

Does anyone know of a better way to get the migrations back in step with the database? We have to do this without losing any data.


Here's the question with the same problem (didn't vote for closing yours as duplicate since the older one does not have an accepted answer):

The solution there is:

  1. Start by referencing your existing MySQL database in database.yml.
  2. run rake db:schema:dump to generate the schema.rb file
  3. Paste the create_table methods from your schema.rb into a new migration, and Voila!

To avoid any inconsistencies you can always check whether the table is already exist, and, if yes, just skip the migration altogether:

class CreateTable < ActiveRecord::Migration
  def change
    unless ActiveRecord::Base.connection.table_exists?('table_name')
      create_table :table_names do |t|
        # some columns