Foreign Key Column Types

Just a quick note — when creating foreign keys in a Rails 5.1+ you should make sure to they are typed as bigint

But why?

Starting in Rails 5.1 primary keys were defaulted to bigintCheck this commit from 2016.  This means that referential foreign keys also need to be bigintIf you’ve gotten into the habit of rails g model Whatever user_id:integer,you need to break it. 

Use user:references or user:belongs_to (which is an alias of references) instead.  These will automatically use bigint and all will be well.

But why???

If you forget to do this or use some kind of gem that generates an integer foreign key your app won’t break yet…

The issue is rooted in this bit I stole from the PostgreSQL docs:

TypeStorage SizeRange
integer4 bytes -2147483648 to +2147483647
bigint8 bytes -9223372036854775808 to 9223372036854775807

bigint is yuge and as a result you could run into a situation where the primary key (a bigint) you’re trying to persist is bigger than the FK column (an integer) can hold.