在Ruby on Rails中,从DB返回的不确定性数据?

时间:2022-10-26 03:19:00

I tried a line:

我试着一行:

last_item = Item.last
last_item.created_at.strftime('%Y-%m-%d')

and the SQL in the console log is:

控制台日志中的SQL是:

SELECT "items".* FROM "items" ORDER BY items.id DESC LIMIT 1

BUT sometimes I get 2011-04-03, and sometimes, 2011-04-04

但有时我得到2011-04-03,有时是2011-04-04

that is really strange. If I print the time out, it is

这真的很奇怪。如果我把时间打印出来,它就是

Sun, 03 Apr 2011 17:58:48 UTC +00:00

2011年4月03日星期日17:58:48 UTC +00:00

what give Rails 3 (3.0.5) this non-deterministic behavior? Is it Time Zone? But I am pressing Reload in the browser and it gives 04-03 this time and next time it gives 04-04 without restarting the server or changing any config file or source code.

什么使Rails 3(3.0.5)具有这种不确定性行为?时区吗?但我在浏览器中按下Reload,它这次和下次都给出04-04,而没有重新启动服务器或修改任何配置文件或源代码。


Update: further debugging show that when it is 04-04, then the time printed using p last_item.created_at is:

更新:进一步调试表明,当它是04-04时,则使用p last_item打印时间。created_at是:

Mon, 04 Apr 2011 01:58:48 HKT +08:00

2011年4月4日星期一01:58:48 HKT +08:00

but I have this line in the view:

但我的观点是:

- Time.zone = '*'

but the last_item.created_at.strftime('%Y-%m-%d') was done in the controller. So shouldn't the controller run first, and in the view, I am merely trying to print it using a different Time zone... also, why will it sometimes become UTC, and sometimes HKT?

但是最后的_item.created_at.strftime('%Y-%m-%d')是在控制器中完成的。所以控制器不应该先运行,在视图中,我只是试图用不同的时区打印它……另外,为什么有时会变成UTC,有时会变成HKT?

1 个解决方案

#1


1  

I think that setting the time zone in the view could cause this non-deterministic behavior. You should try setting your time zone somewhere in the config directory, perhaps in config/application.rb.

我认为在视图中设置时区会导致这种不确定性行为。您应该尝试在config/application.rb中设置时区。

#1


1  

I think that setting the time zone in the view could cause this non-deterministic behavior. You should try setting your time zone somewhere in the config directory, perhaps in config/application.rb.

我认为在视图中设置时区会导致这种不确定性行为。您应该尝试在config/application.rb中设置时区。