Skip to content

Commit b1b9d05

Browse files
committed
Add Columns With Default Values Are Nil On Create as a rails til
1 parent 0598206 commit b1b9d05

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1212

13-
_1015 TILs and counting..._
13+
_1016 TILs and counting..._
1414

1515
---
1616

@@ -619,6 +619,7 @@ _1015 TILs and counting..._
619619
- [Check If ActiveRecord Update Fails](rails/check-if-activerecord-update-fails.md)
620620
- [Check Specific Attributes On ActiveRecord Array](rails/check-specific-attributes-on-activerecord-array.md)
621621
- [Code Statistics For An Application](rails/code-statistics-for-an-application.md)
622+
- [Columns With Default Values Are Nil On Create](rails/columns-with-default-values-are-nil-on-create.md)
622623
- [Comparing DateTimes Down To Second Precision](rails/comparing-datetimes-down-to-second-precision.md)
623624
- [Conditional Class Selectors in Haml](rails/conditional-class-selectors-in-haml.md)
624625
- [Convert A Symbol To A Constant](rails/convert-a-symbol-to-a-constant.md)
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Columns With Default Values Are Nil On Create
2+
3+
Let's say I have a `MagicLinks` model backed by `magic_links` Postgres table.
4+
Both the `id` and `token` columns are of type `UUID` and have default values of
5+
`gen_random_uuid()`. That means from the Rails-side when I go to create a
6+
`MagicLink` record, I don't have to think about specifying values for `id` or
7+
`token` -- the DB will take care of that.
8+
9+
```ruby
10+
> magic_link = MagicLink.create(expires_at: Time.zone.now, user: User.last)
11+
User Load (5.9ms) SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT $1 [["LIMIT", 1]]
12+
TRANSACTION (0.1ms) BEGIN
13+
MagicLink Create (3.1ms) INSERT INTO "magic_links" ("user_id", "expires_at", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"
14+
...
15+
16+
> magic_link.id
17+
=> "6c6dddbf-4427-407d-8dc8-eef8cb65d491"
18+
> magic_link.token
19+
=> nil
20+
```
21+
22+
This `create` call is translated into an `insert` SQL statement that includes a
23+
`returning` clause. For `create` it is always `returning "id"`. This means that
24+
the `UUID` value generated in Postgres-land for `id` gets passed back into the
25+
ActiveRecord instance. The `UUID` value generated for `token`, however, is not
26+
because `token` isn't specified in the `returning` clause.
27+
28+
[source](https://github.com/rails/rails/issues/17605)

0 commit comments

Comments
 (0)