문제

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
도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top