Rails中的时间字段变回空白 [英] Time fields in Rails coming back blank
问题描述
我有一个在Sqlite3上运行的简单Rails 3.b1(Ruby 1.9.1)应用程序.我有这张桌子:
I have a simple Rails 3.b1 (Ruby 1.9.1) application running on Sqlite3. I have this table:
create_table :time_tests do |t|
t.time :time
end
我看到这种行为:
irb(main):001:0> tt = TimeTest.new
=> #<TimeTest id: nil, time: nil>
irb(main):002:0> tt.time = Time.zone.now
=> Mon, 03 May 2010 20:13:21 UTC +00:00
irb(main):003:0> tt.save
=> true
irb(main):004:0> TimeTest.find(:first)
=> #<TimeTest id: 1, time: "2000-01-01 20:13:21">
因此,时间回到了空白.检查表,数据看起来正常:
So, the time is coming back blank. Checking the table, the data looks OK:
sqlite> select * from time_tests;
1|2010-05-03 20:13:21.774741
我想这是在检索部分?这是怎么回事?
I guess it's on the retrieval part? What's going on here?
推荐答案
从技术上来说,它不会再空白.它以默认日期的时间返回.它返回2000-01-01 20:13:21
作为预期的时间.
Technically, it's not coming back blank. It comes back as a time with a default date. It returns 2000-01-01 20:13:21
as the time, which is expected.
Rails正在将数据神奇地加载到Time对象中并清除日期(因为您只告诉它存储时间).
Rails is doing some magic loading of the data into a Time object and clearing out the date (since you only told it to store the time).
如果要存储日期和时间,则需要将列定义为datetime
.相反,如果您只想约会,可以使用date
.
If you want to store the date and time then you need to define the column as a datetime
. And conversely, if you wanted just a date you would use date
.
所以回顾一下:
date => "2010-12-12 00:00:00"
time => "2000-01-01 13:14:15"
datetime => "2010-12-12 13:14:15"
这篇关于Rails中的时间字段变回空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!