2013-12-10 45 views
0

我有一個在不同數據庫上運行的Rails應用程序取決於客戶端首選項。我有一個「catalog_item_specifications」表,它有一個「bec_id」列。該列的類型是字符串。現在我想將列的類型更改爲整數。當我寫:Rails更改MySQL和Postgres的列類型遷移

change_column :catalog_item_specifications, :bec_id, :integer 

它在MySQL上工作正常,但在postgres上失敗。所以根據這個帖子:Rails - gmaps4rails gem on postgres 我改變了我的遷移以下內容:

connection.execute(%q{ 
    alter table catalog_item_specifications 
    alter column bec_id 
    type integer using bec_id::integer 
}) 

現在對Postgres的工作,但未能在MySQL。我需要一個解決方案(不丟棄和重新添加),這將適用於兩者。

回答

1

這是您可能最適合檢查運行哪個數據庫引擎的情況之一,然後使用適用於該引擎的命令。

事情是這樣的:

if connection.adapter_name.downcase == 'postgresql' 
    connection.execute(%q{ 
    alter table catalog_item_specifications 
    alter column bec_id 
    type integer using bec_id::integer 
    }) 
else 
    change_column :catalog_item_specifications, :bec_id, :integer 
end 

哪裏'postgresql'是ADAPTER_NAME(你必須進行檢查,看它實際上是什麼,當你對遷移的Postgres)。

+0

我實際上最終得到了這個解決方案,而不是在這裏看到相同的答案。很高興知道我在正確的軌道上! –