Reputation: 4783
Say I have a simple ActiveRecord model with this example schema:
create_table "users", id: :serial do |t|
t.datetime "updated_at"
end
When I run the following code in the console:
user = User.new
user.updated_at = DateTime.now
user.updated_at # => Thu, 27 Feb 2020 09:28:51 GMT +00:00
My question is: why this output is different than the normal return value of DateTime.now
, which is
DateTime.now # => Thu, 27 Feb 2020 10:28:51 +0100
Is there some kind of serializer involved? How can I find out more about this?
Upvotes: 1
Views: 31
Reputation: 341
add your time zone in your config/application.rb inside the
class Application < Rails::Application
.......
# it will be like this
config.time_zone = "Asia/Riyadh"
.....
end
Upvotes: 0
Reputation: 1776
AR updated_at/created_at are time zone aware attributes. You can read more about them here:
https://api.rubyonrails.org/classes/ActiveRecord/Timestamp.html
If you grab a User record for instance, and call time_zone_aware_types
on it, you'll get the timezone aware column types
user = User.first
user.time_zone_aware_types
=> [:datetime, :time]
These types of columns are automatically converted to Time.zone
when retrieved from the database even though they are stored in UTC.
The difference with DateTime.now
is that it's not timezone aware and just returns the time in UTC
Upvotes: 1