2016-02-12 118 views
2

rake db:migratesqlite3本地工作,但在heroku中不工作postgresqlPG :: UndefinedTable:错误:关系“音乐家”不存在

错误

PG::UndefinedTable: ERROR: relation "musicians" does not exist 
: ALTER TABLE "orders" ADD CONSTRAINT "fk_rails_ad134589be" 
FOREIGN KEY ("musician_id") 
    REFERENCES "musicians" ("id") 
    (0.9ms) ROLLBACK 
rake aborted! 
StandardError: An error has occurred, this and all later migrations canceled: 
PG::UndefinedTable: ERROR: relation "musicians" does not exist 
: ALTER TABLE "orders" ADD CONSTRAINT "fk_rails_ad134589be" 
FOREIGN KEY ("musician_id") 

这里是整个日志的链接:https://gist.github.com/helloravi/2cb69e0927e63e186b09

下面是没有得到执行迁移。显示错误下面的迁移代码

class CreateAlbums < ActiveRecord::Migration 
    def change 
    create_table :albums do |t| 
     t.string :album_name 
     t.references :musician, index: true, foreign_key: true 
     t.timestamps null: false 
    end 
    add_foreign_key :albums, :users, column: :musician_id 
    end 
end 

我有一个音乐家列是布尔(有些用户音乐家)

我甚至使用add_foreign_key尝试,仍然我不能图users表解决问题是什么。

我试图rake db:schema:load和它的工作。我希望能够使rake db:migrate工作,因为我需要能够在生产中迁移。

+0

您运行'heroku运行耙db:migrate'? – Pavan

+0

这就是不工作帕 –

+0

难道你还贴在'应用程序/模型/ album.rb'协会的一部分? –

回答

3

SQLite不检查外键,它只是忽略它们。但是,当外键约束无效时,PostgreSQL非常严格并引发错误。

Rails的foreign_key不支持你想让它做什么。当你写t.references :musician那么必须有一个musicians表。但您希望外键指向users表。

我看到两个选项:

  1. 使用t.references :users并在albums.rb重命名该协会是这样的:

    belongs_to :musician, class_name: 'User', foreign_key: 'user_id' 
    
  2. 或者:你刚才用t.integer :musician_id代替references并定义外键与execute 'ALTER TABLE ...'

手动约束
+0

1.我可能会用一个选项去。我已经按照您的建议使用了该协会。 2.如何手动执行'执行'ALTER TABLE ...''in heroku? 3.如果我使用t.references删除了该行并在迁移中使用了“add_foreign_key”行,它会起作用吗? –

1

@spickermann说的是正确的。 更改您的迁移到以下应该工作:

class CreateAlbums < ActiveRecord::Migration 
    def change 
    create_table :albums do |t| 
     t.string :album_name 
     t.integer :musician_id 
     t.timestamps null: false 
    end 
    add_foreign_key :albums, :users, column: :musician_id 
    add_index :albums, :musician_id 
    end 
end 
+0

什么是会创建你所提到的迁移的命令?(我也计划做什么Speckerman说) –

+0

你可以编辑迁移。现有的迁移将无法在postgresql上运行。您将不得不对现有迁移进行更改。进行此更改不会影响sqlite3发生的情况。 –

+0

我现在要求的是未来的命令。现在我只是采取这个建议:) –

相关问题