【问题标题】:Rails - MySQL auto increment id column type changeRails - MySQL 自动增量 id 列类型更改
【发布时间】:2015-12-26 19:23:29
【问题描述】:

我有一个包含大量模型和数据库表的 Rails 网站。 在所有这些中,我想将 :id 主键列更改为 bigint 而不是 int,因为它即将超过 MySQL 的整数 int(11) 限制。

我不想使用其他帖子中建议的方法,他们建议我们在创建表和添加自定义列时执行 :id => false 并添加自定义列 :id 指定大小。

我已经有很多数据,我不希望 id 列 ids 也发生变化,因为我将它用于一些 has_many belongs_to 关系并且可能会破坏所有链接。

请建议我如何在不重新创建表和/或丢失数据和 id 值的情况下将_column id 从 int(11) 更改为 bigint

【问题讨论】:

    标签: mysql ruby-on-rails database biginteger integer-overflow


    【解决方案1】:

    不要忘记auto_increment: true

    class NameOfYourMigration < ActiveRecord::Migration
      def up
        change_column :table_name, :id, :integer, limit: 8, auto_increment: true
      end
    
      def down
        change_column :table_name, :id, :integer, auto_increment: true
      end
    end
    

    【讨论】:

    • 忘记auto_increment = 痛苦的世界。
    【解决方案2】:

    试试看

    进行如下所示的迁移:

    class NameOfYourMigration < ActiveRecord::Migration
    
        def up
            change_column :table_name, :id, :integer, limit: 8 # <-- makes the column type bigint
        end
    
        def down
            change_column :table_name, :id, :integer
        end
    
    end
    

    【讨论】:

      猜你喜欢
      • 2021-03-03
      • 2012-02-08
      • 1970-01-01
      • 2021-05-01
      • 1970-01-01
      • 2014-10-01
      • 2015-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多