Rails 中的时间字段返回空白

发布于 2024-08-31 01:04:00 字数 641 浏览 3 评论 0原文

我有一个在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

完美的未来在梦里 2024-09-07 01:04:00

从技术上来说,它不会返回空白。它返回为带有默认日期的时间。它返回 2000-01-01 20:13:21 作为时间,这是预期的。

Rails 正在执行一些神奇的操作,将数据加载到 Time 对象中并清除日期(因为您只告诉它存储时间)。

如果您想存储日期和时间,则需要将该列定义为日期时间。相反,如果您只想要一个日期,则可以使用date

回顾一下:

date => "2010-12-12 00:00:00"
time => "2000-01-01 13:14:15"
datetime => "2010-12-12 13:14:15"

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 use date.

So to recap:

date => "2010-12-12 00:00:00"
time => "2000-01-01 13:14:15"
datetime => "2010-12-12 13:14:15"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文