【问题标题】:RoR: Cannot change_column in postgres, fine in MySQL (MySQL for development, Postgres on Heroku)RoR:不能在 postgres 中更改_column,在 MySQL 中很好(用于开发的 MySQL,Heroku 上的 Postgres)
【发布时间】:2023-04-02 08:53:01
【问题描述】:

我有一个专栏叫“奖品”:

create_table :contests do |t|
  t.text :prize

我最近意识到这将始终是一个整数,我想设置一个默认值:

def change
  change_column :contests, :prize, :integer, :default => 200

这在我使用 MySQL DB 的本地机器上运行良好。但是,当我推送到我的生产站点(托管在 Heroku 上,它为我提供 Postgres DB)时,我收到以下错误:

PGError: ERROR:  column "prize" cannot be cast to type "pg_catalog.int4"
: ALTER TABLE "contests" ALTER COLUMN "prize" TYPE integer

在这篇文章中:http://www.postgresonline.com/periodical.php?i_id=3 他们讨论了使用 USING 来解决这个问题。但我不知道我该怎么做,以及这是否适合我正在尝试做的事情。

非常感谢您对解决此问题的任何见解。

谢谢! 林哥

【问题讨论】:

  • 只有当奖品列中的所有值都可以转换为整数时,您的代码才能工作,另请参阅this answer
  • 您是否有任何理由不使用与生产相同的数据库进行开发?

标签: mysql ruby-on-rails ruby postgresql activerecord


【解决方案1】:

首先你应该在两个环境中使用相同的数据库来防止这种意外。

要在迁移中运行原始 sql,请参阅此示例 http://guides.rubyonrails.org/migrations.html#using-the-up-down-methods

【讨论】:

    【解决方案2】:

    我认为你必须手动完成:

    def up
        connection.execute(%q{
            alter table contests
            alter column prize type integer using cast(prize as integer),
            alter column price set default 200
        })
    end
    

    如果您想在 MySQL 和 PostgreSQL 中运行相同的迁移,那么:

    def up
        case ActiveRecord::Base.connection
        when ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
            connection.execute(%q{
                alter table contests
                alter column prize type integer using cast(prize as integer),
                alter column price set default 200
            })
        when ActiveRecord::ConnectionAdapters::MySQLAdapter
            # MySQL version...
        end
    end
    

    一旦您解决了这个问题,您的下一个任务就是将您的开发环境切换到 PostgreSQL,以便您可以开始修复所有其他小问题(例如 GROUP BY 问题、区分大小写的 LIKE、列截断行为、. ..) 你会遇到的。

    【讨论】:

    • 我收到这个错误:Mysql2::Error: You have an error in your SQL syntax;检查与您的 MySQL 服务器版本相对应的手册,以了解在 'type integer using cast(prize as integer) 附近使用的正确语法
    • @RingoBlancke:对于不同的数据库,您必须在迁移中使用不同的东西。检查我的更新。
    猜你喜欢
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 2012-08-25
    • 2012-09-08
    • 1970-01-01
    • 2014-05-13
    • 2022-08-18
    • 2011-03-20
    相关资源
    最近更新 更多