Skip to content

Commit 9f39c01

Browse files
authored
Merge pull request rails#53687 from andyatkinson/docs/rails-guides-postgresql-timestamp-with-time-zone
Rails Guides: PostgreSQL timestamp with time zone [ci skip]
2 parents 5ea8bd3 + f65d592 commit 9f39c01

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

guides/source/active_record_postgresql.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -516,6 +516,34 @@ irb> event.duration
516516
=> 2 days
517517
```
518518

519+
### Timestamps
520+
521+
* [Date/Time Types](https://www.postgresql.org/docs/current/datatype-datetime.html)
522+
523+
Rails migrations with timestamps store the time a model was created or updated. By default and for legacy reasons, the columns use the `timestamp without time zone` data type.
524+
525+
```ruby
526+
# db/migrate/20241220144913_create_devices.rb
527+
create_table :post, id: :uuid do |t|
528+
t.datetime :published_at
529+
# By default, Active Record will set the data type of this column to `timestamp without time zone`.
530+
end
531+
```
532+
533+
While this works ok, [PostgreSQL best practices](https://wiki.postgresql.org/wiki/Don't_Do_This#Don.27t_use_timestamp_.28without_time_zone.29) recommend that `timestamp with time zone` is used instead for timezone-aware timestamps.
534+
This must be configured before it can be used for new migrations.
535+
536+
To configure `timestamp with time zone` as your new timestamp default data type, place the following configuration in the `config/application.rb` file.
537+
538+
```ruby
539+
# config/application.rb
540+
ActiveSupport.on_load(:active_record_postgresqladapter) do
541+
self.datetime_type = :timestamptz
542+
end
543+
```
544+
545+
With that configuration in place, generate and apply new migrations, then verify their timestamps use the `timestamp with time zone` data type.
546+
519547
UUID Primary Keys
520548
-----------------
521549

0 commit comments

Comments
 (0)