mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 23:28:02 +00:00
Add Create Table With bigint Id As Primary Key as a Rails TIL
This commit is contained in:
@@ -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)
|
||||
|
||||
30
rails/create-table-with-bigint-id-as-primary-key.md
Normal file
30
rails/create-table-with-bigint-id-as-primary-key.md
Normal file
@@ -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)
|
||||
Reference in New Issue
Block a user