2012-09-26 47 views
20

我試圖執行跟進遷移更改「推」模式的表Rails的遷移錯誤瓦特/ Postgres的推到Heroku的

class ChangeDataTypeForTweetsNumber < ActiveRecord::Migration 
    def up 
    change_column :tweets do |t| 
     t.change :number, :integer 
    end 
    end 

    def down 
    change_table :tweets do |t| 
     t.change :number, :string 
    end 
    end 
end 

列「數字」在執行時將跟進遷移到Heroku的....

heroku rake db:migrate:up VERSION=20120925211232 

我收到以下錯誤

PG::Error: ERROR: column "number" cannot be cast to type integer 
: ALTER TABLE "tweets" ALTER COLUMN "number" TYPE integer 

有什麼想法你有將非常感激。

謝謝大家。

回答

31

fine manual

[ALTER TABLE ... ALTER COLUMN ...]
可選USING子句指定如何計算從舊的新的列值;如果省略,則默認轉換與從舊數據類型到新轉換的賦值相同。如果不存在從舊類型到新類型的隱式或賦值轉換,則必須提供USING子句。

有來自varchar在PostgreSQL裏沒有隱式轉換爲int所以抱怨column "number" cannot be cast to type integer和ALTER TABLE失敗。您需要告訴PostgreSQL如何將舊字符串轉換爲數字以匹配新列類型,這意味着您需要在ALTER TABLE中獲得USING子句。我不知道有什麼辦法讓Rails的爲你做的,但你可以用手輕易夠做到這一點:

def up 
    connection.execute(%q{ 
    alter table tweets 
    alter column number 
    type integer using cast(number as integer) 
    }) 
end 

你要注意的是不能轉換爲整數值, PostgreSQL會讓你知道是否有問題,你必須在遷移成功之前解決它們。

您現有的向下遷移應該沒問題,應將integer轉換爲varchar應自動處理。

+0

非常有趣 - 謝謝! – dougiebuckets

+0

要了解更簡潔和習慣的方法,請查看下面的riley答案! – danmaz74

+0

@ danmaz74:你知道這是在2012年推出還是我錯過了什麼? –

46

同上,但一點點更簡潔:

change_column :yourtable, :column_to_change, 'integer USING CAST("column_to_change" AS integer)' 
+0

感覺像AR應該處理這個真的 – Rob

+1

在這種情況下使用這個可逆遷移: 'reversible do | dir | dir.up do change_column:yourtable,:column_to_change,'integer USING CAST(「column_to_change」AS integer)' end dir。向下做 change_column:yourtable,:column_to_change,'字符變化USING CAST(「column_to_change」AS字符變化)' end end' – febeling