Rails 中的时间字段返回空白
我有一个在 Sqlite3 上运行的简单 Rails 3.b1 (Ruby 1.9.1) 应用程序。我有这张表:
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">
所以,时间回来了空白。检查表,数据看起来不错:
sqlite> select * from time_tests;
1|2010-05-03 20:13:21.774741
我猜它在检索部分?这是怎么回事?
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
And I see this behavior:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从技术上来说,它不会返回空白。它返回为带有默认日期的时间。它返回
2000-01-01 20:13:21
作为时间,这是预期的。Rails 正在执行一些神奇的操作,将数据加载到 Time 对象中并清除日期(因为您只告诉它存储时间)。
如果您想存储日期和时间,则需要将该列定义为日期时间。相反,如果您只想要一个日期,则可以使用
date
。回顾一下:
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 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).
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 usedate
.So to recap: