Rails更改MySQL和Postgres的列类型迁移

时间:2013-12-10 06:51:51

标签: mysql sql ruby-on-rails postgresql migration

我有一个在不同数据库上运行的rails应用程序取决于客户端首选项。我有一个“catalog_item_specifications”表,其中有一列“bec_id”。列的类型是字符串。现在我想将列的类型更改为整数。我写的时候:

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 个答案:

答案 0 :(得分: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时的实际情况)。