From 9bbde247a56bfd09d2e73dbd4f266aea0db7ce8a Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sat, 9 Nov 2024 17:28:47 -0600 Subject: [PATCH] Add Create Table With bigint Id As Primary Key as a Rails TIL --- README.md | 3 +- ...ate-table-with-bigint-id-as-primary-key.md | 30 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 rails/create-table-with-bigint-id-as-primary-key.md diff --git a/README.md b/README.md index 57aa2d3..815bbef 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1501 TILs and counting..._ +_1502 TILs and counting..._ --- @@ -929,6 +929,7 @@ _1501 TILs and counting..._ - [Count The Number Of Records By Attribute](rails/count-the-number-of-records-by-attribute.md) - [Create A Custom Named References Column](rails/create-a-custom-named-references-column.md) - [Create A Join Table With The Migration DSL](rails/create-a-join-table-with-the-migration-dsl.md) +- [Create Table With bigint Id As Primary Key](rails/create-table-with-bigint-id-as-primary-key.md) - [Creating Records of Has_One Associations](rails/creating-records-of-has-one-associations.md) - [Custom Validation Message](rails/custom-validation-message.md) - [Customize Paths And Helpers For Devise Routes](rails/customize-paths-and-helpers-for-devise-routes.md) diff --git a/rails/create-table-with-bigint-id-as-primary-key.md b/rails/create-table-with-bigint-id-as-primary-key.md new file mode 100644 index 0000000..f57d2e9 --- /dev/null +++ b/rails/create-table-with-bigint-id-as-primary-key.md @@ -0,0 +1,30 @@ +# Create Table With bigint ID As Primary Key + +When creating a new table with an ActiveRecord migration, we specify all the +fields _except_ the `id`. The `id`, which is the primary key, is implicit. We +get it by default. + +The type of that `id` defaults to `int` which is a 32-bit signed integer. + +We can override the type of `id` in a variety of ways. The one I prefer in most +cases is to make the `id` of type `bigint`. This is a 64-bit signed integer. It +offers quite a bit more headroom for the number of unique identifies in our +table. + +This can be specified by including `id: :bigint` as an option to the +`create_table` method. + +```rails +class CreatePosts < ActiveRecord::Migration[8.0] + def change + create_table :posts, id: :bigint do |t| + t.string :title, null: false + t.string :body, null: false + + t.timestamps + end + end +end +``` + +[source](https://api.rubyonrails.org/v7.1/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-create_table)