Skip to content

Commit f65d592

Browse files
andyatkinsonEdouard-chin
authored andcommitted
[ci-skip] Rails Guides: PostgreSQL timestamp with time zone
This guide addition documents how to configure your Rails application to use the data type "timestamp with time zone" (timezone-aware timestamp), instead of the default type, "timestamp without time zone" Support for this data type was added earlier in Active Record, but requires a configuration change in order to use, and from these PR comments, where, why, and how to perform this configuration change wasn't added to the Rails Guides Active Record PostgreSQL documentation from what I could tell Related PR: rails#41084 Guide page: https://guides.rubyonrails.org/active_record_postgresql.html PostgreSQL best practices: https://wiki.postgresql.org/wiki/Don't_Do_This#Don.27t_use_timestamp_.28without_time_zone.29
1 parent 5ea8bd3 commit f65d592

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)