Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How to use BIGINT as Primary Key

I've read through a lot of articles discussing how to use BIGINT as primary keys in Rails, but it seems like all of them are outdated.

How can I use BIGINT's for my primary keys, preferrably by just setting this globally. (i am aware of the differences in performance)

Things I've tried:

  • http://www.mccartie.com/2016/12/05/rails-5.1.html
  • https://moeffju.net/blog/bigints-in-rails-as-primary-keys
  • and a lot more I cannot remember
like image 695
heroxav Avatar asked Mar 08 '17 14:03

heroxav


2 Answers

If your app was natively built in rails '>= 5.1', your primary keys should already be BIGINT. By "natively built" I mean that your migrations were initially run with that Rails version (as opposed to running them in < 5.1 and then updating the gem later)

If they are not already BIGINT, you can use the migration action found in the source below, pasted here for convenience:

change_column :your_table_name, :id, :bigint

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

like image 158
armahillo Avatar answered Sep 28 '22 20:09

armahillo


Have you tries this code in migration file?

  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

And in model:

class ModelName < ApplicationRecord
  self.primary_key = :id
end
like image 27
sreang rathanak Avatar answered Sep 28 '22 18:09

sreang rathanak