在Heroku上创建表失败——迁移在本地工作,但在Heroku上失败



我正在Rails 3应用程序上工作,并试图运行迁移。我正在尝试创建一个名为Songs的表,我能够成功地创建表并在本地迁移。然而,当我将代码推送到Heroku并迁移到那里时,我遇到的错误是:

** Execute db:migrate
==  CreateSongs: migrating ====================================================
-- create_table(:songs)
NOTICE:  CREATE TABLE will create implicit sequence "songs_id_seq1" for serial column "songs.id"
rake aborted!
An error has occurred, this and all later migrations canceled:
PG::DuplicateTable: ERROR:  relation "songs" already exists
: CREATE TABLE "songs" ("id" serial primary key, "solo_cello" character varying(255), "created_at" timestamp, "updated_at" timestamp) /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.1.12/lib/active_record/connection_adapters/postgresql_adapter.rb:605:in `async_exec'

我意识到这个错误源于数据库中已经存在的表,但是当我运行

 heroku run "bundle exec rake db:schema:dump && cat db/schema.rb" 

我看到模式版本在ActiveRecord:: schema .define(:version => 20130915155113),并且创建Songs模型的迁移发生在此迁移之后(它是20140506043817)。

这是我的本地模式的截断版本:

 ActiveRecord::Schema.define(:version => 20140511155456) do
 [other tables...] 
create_table "songs", :force => true do |t|
  t.string   "solo_cello"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "solo_violin"
  t.string   "duo_one"
  t.string   "duo_two"
  t.string   "trio_a_one"
  t.string   "trio_a_two"
  t.string   "trio_a_three"
  t.string   "trio_b_one"
  t.string   "trio_b_two"
  t.string   "trio_b_three"
  t.string   "quartet_one"
  t.string   "quartet_two"
  t.string   "quartet_three"
  t.string   "quartet_four"
end
以下是我的问题:
  1. 如果数据库上的模式是20130915155113版本,如果创建Song表(20140506043817)的迁移是稍后进行的,那么表如何已经存在?

  2. 我需要做些什么来运行成功的迁移?我意识到我可以删除数据库(这是登台环境),但我非常不希望在生产环境中这样做。

  3. 为什么迁移在本地机器上工作得很好,但在Heroku上却不行?

听起来您的歌曲表可能由于恢复数据库备份而被留下了。在Heroku上恢复数据库备份只会重写备份中存在的表,但不会删除创建备份时还不存在的表。

有几个步骤可以解决这个问题:

  1. 删除表。您可以在终端上执行heroku pg:psql,然后执行查询DROP TABLE songs;,手动删除表。如果这是唯一有问题的表,那么现在可以运行迁移了。

  2. 删除数据库。如果你有一个数据库备份,你可以承受一些停机时间,你也可以通过从终端运行heroku pg:reset来删除数据库,然后恢复你的数据库备份并运行你的迁移。

最新更新