前提是我在application.rb
中已经加入了:
config.time_zone = 'Beijing'
config.active_record.default_timezone = :local
我在 rails console 中查询用户的登录日志,返回的创建时间是: 2017-05-10 15:13:10
irb(main):001:0> User.find(2).user_signin_logs.order(created_at: :desc).first
User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1
UserSigninLog Load (0.6ms) SELECT `user_signin_logs`.* FROM `user_signin_logs` WHERE `user_signin_logs`.`user_id` = 2 ORDER BY `user_signin_logs`.`created_at` DESC LIMIT 1
=> #<UserSigninLog id: "2e20a942-3593-11e7-8338-00163e01107f", user_id: 2, ip: "27.17.98.36", ip_country: "中国", ip_province: "湖北", ip_city: "武汉", created_at: "2017-05-10 15:13:10", updated_at: "2017-05-10 15:13:10">
我用同样的 sql 语句直接去查数据库,得到的结果却是:2017-05-10 23:13:10
mysql> SELECT `user_signin_logs`.* FROM `user_signin_logs` WHERE `user_signin_logs`.`user_id` = 2 ORDER BY `user_signin_logs`.`created_at` DESC LIMIT 1;
+--------------------------------------+---------+------------+-------------+-----------+--------------+---------------------+---------------------+
| id | user_id | ip | ip_country | ip_province | ip_city | created_at | updated_at |
+--------------------------------------+---------+------------+-------------+-----------+--------------+---------------------+---------------------+
| 2e20a942-3593-11e7-8338-00163e01107f | 2 | 中国 | 湖北 | 武汉 | 2017-05-10 23:13:10 | 2017-05-10 23:13:10 |
+--------------------------------------+---------+------------+-------------+-----------+--------------+---------------------+---------------------+
1 row in set (0.02 sec)
看了 @boyishwei 的贴子 Rails 中的时区及时间问题 了解到created_at
字段不管有没有设置 config.active_record.default_timezone = :local
都会记录 UTC 时间。
所以我的问题是,如何让created_at
在 console 里默认就显示 localtime?而不是每次都要加.localtime
或 .getlocal('+08:00')
。
多谢回复。