6

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:

heroxav
  • 1,387
  • 1
  • 22
  • 65

2 Answers2

17

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

armahillo
  • 306
  • 2
  • 5
  • I looked at that article before, but is explicitly speaks about Rails > 5.1. As I've stated in the post, I am using Rails 5.0.2. As far as I know, Rails 5.1 has not been released on rubygems yet... – heroxav Mar 08 '17 at 17:10
  • Whoops! Sorry, I misread. That said, did you try the migration? – armahillo Mar 08 '17 at 22:21
  • Tried it on rails 4.2 and it works smoothly :) Thanks a ton! – cesartalves Dec 02 '19 at 17:59
1

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
sreang rathanak
  • 502
  • 1
  • 4
  • 15
  • 1
    What is `"pk_table_name"`? And as far is I know `t.integer :id, limit: 8` is the correct expression for a BIGINT in Rails, or is that a Rails 5.1 thing? – heroxav Mar 08 '17 at 17:13
  • yes you are right: `t.integer :id, limit: 5, null: false, options: 'PRIMARY KEY'` and `pk_table_name ` is the indexing name. – sreang rathanak Mar 09 '17 at 00:17