Rails: 如何使用 BIGINT 作为主键

Rails: How to use BIGINT as Primary Key

我阅读了很多讨论如何在 Rails 中使用 BIGINT 作为主键的文章,但似乎所有文章都已过时。

如何将 BIGINT 用作我的主键,最好是全局设置。 (我知道性能上的差异)

我尝试过的事情:

你在迁移文件中尝试过这段代码吗?

  def change
    create_table :table_name, id: false do |t|
      t.bigint :id, null: false
      t.index :id, name: "pk_table_name", unique: true
    end
  end

模型中:

class ModelName < ApplicationRecord
  self.primary_key = :id
end

如果您的应用是在 rails '>= 5.1' 中原生构建的,您的主键应该已经是 BIGINT。 "natively built" 我的意思是你的迁移最初是 运行 那个 Rails 版本(而不是 运行 在 < 5.1 中安装它们然后更新 gem )

如果它们还没有 BIGINT,您可以使用在下面的源中找到的迁移操作,为方便起见粘贴在这里:

change_column :your_table_name, :id, :bigint

来源:http://www.mccartie.com/2016/12/05/rails-5.1.html