Question

I am trying to repurpose a table that was previously used for something else. So I'm creating a migration to remove the table and start fresh with new columns. However, I'm running into an issue where if I roll back the migration and run it again, I get errors because the table has already been dropped. How can I get around this?

class CreateNewTeams < ActiveRecord::Migration
  def self.up
    drop_table :teams
    create_table :teams do |f|
      # ...
    end
  end

  def self.down
    drop_table :teams
  end
end
Was it helpful?

Solution

force option was built for dropping the table before creating (if it exists). See docs

class CreateNewTeams < ActiveRecord::Migration
  def self.up
    create_table :teams, :force => true do |f|
      # new columns
    end
  end

  def self.down
    create_table :teams, :force => true do |f|
      # old columns
    end 
  end
end

OTHER TIPS

Your down should leave the database in the state before the migration was run. So in your case,

class CreateNewTeams < ActiveRecord::Migration
  def self.up
    drop_table :teams
    create_table :teams do |f|
      # new purpose
    end
  end

  def self.down
    drop_table :teams
    create_table :teams do |f|
      # old purpose
    end
  end
end

If all you need to change is to rename some columns, do it without dropping the table. If you are doing this on an application that is live and used extensively, deploying this change is going to cause downtime. Keep that in mind too

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top