【发布时间】:2018-03-20 06:51:45
【问题描述】:
我使用 postgresql 作为我的数据库。
目前我有计时模型,其中包含open_at 和close_at 字段。两个字段的数据类型都是时间。
2.4.2 :077 > Time.current
=> Tue, 20 Mar 2018 06:46:28 UTC +00:00
=> #<Timing id: 3, day: "Tuesday", open_at: "2000-01-01 04:00:00", close_at: "2000-01-01 01:00:00", warehouse_id: 9, created_at: "2018-03-19 10:45:36", updated_at: "2018-03-20 06:34:16">
以上计时记录的开放时间为凌晨4点,关闭时间为凌晨1点。当前时间是 6 点 46 分。所以当我做下面的查询时
2.4.2 :079 > Timing.where("open_at < ? and close_at > ?", Time.current, Time.current)
Timing Load (0.7ms) SELECT "timings".* FROM "timings" WHERE (open_at < '2018-03-20 06:48:09.004429' and close_at > '2018-03-20 06:48:09.004496') LIMIT $1 [["LIMIT", 11]]
=> #<ActiveRecord::Relation []>
它应该是结果,但结果是空的,但是当我将关闭时间更改为晚上 11 点时,意味着 23:00:00。并在查询下方运行
Timing.where("open_at < ? and close_at > ?", Time.current, Time.current)
Timing Load (0.8ms) SELECT "timings".* FROM "timings" WHERE (open_at < '2018-03-20 06:49:12.307156' and close_at > '2018-03-20 06:49:12.307205') LIMIT $1 [["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<Timing id: 3, day: "Tuesday", open_at: "2000-01-01 04:00:00", close_at: "2000-01-01 23:59:00", warehouse_id: 9, created_at: "2018-03-19 10:45:36", updated_at: "2018-03-20 06:49:07">]>
结果来了。谁能解释时间有什么问题?或者如果我想获得正确的记录应该如何查询
**
更新 - 在 schema.rb 中添加时序表
**
schema.rb
create_table "timings", force: :cascade do |t|
t.string "day"
t.time "open_at"
t.time "close_at"
t.bigint "warehouse_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["warehouse_id"], name: "index_timings_on_warehouse_id"
end
【问题讨论】:
-
可能问题出在时间格式上。如果我没记错数据库总是以 24 小时格式存储时间,所以你的关闭时间小于打开时间(在第一种情况下)。
-
@kunashir 是的,你是对的。但是如何解决这个问题?
-
使用
time格式而不是datetimepostgresql.org/docs/9.1/static/datatype-datetime.html -
@meta 当前字段的数据类型是时间。并且只检查当前时间。所以可能不是问题
-
不,这显然是
datetime(PQ 术语中的timestamp)格式:“2000-01-01 04:00:00”,您需要的是time,它看起来像这个“04:00:00”
标签: ruby-on-rails postgresql ruby-on-rails-5