2016-02-12 112 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

我現在要求的是未來的命令。現在我只是採取這個建議:) –

相關問題