5

我很困惑可能出了什么问题。

我已登录heroku run console并尝试更新数据库上的时间戳。

我跑去User.find(6)看到用户有一个:next_click = 2000-01-01...我不知道为什么它是那个值,但无论如何,我知道User.update 6, {:next_click => Time.utc(2015)}它似乎正确更新说2015-01-01 00:00:00,但是当我做另一个User.find(6)时,时间似乎已经切换回来,因为它不是2015-01-01 00:00:00

我真的很困惑为什么不是。有什么见解吗?

见附件截图在此处输入图像描述

irb(main):033:0> User.update 6, {:next_click => Time.utc(2015) }
  User Load (34.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 6]]
   (1.8ms)  BEGIN
   (2.2ms)  UPDATE "users" SET "next_click" = '2015-01-01 00:00:00.000000', "updated_at" = '2012-05-24 00:13:26.197358' WHERE "users"."id" = 6
   (2.2ms)  COMMIT
=> #<User id: 6, name: "mazlix", gold: 10, points: 10, next_click: "2015-01-01 00:00:00", created_at: "2012-05-23 23:40:39", updated_at: "2012-05-24 00:13:26">
irb(main):034:0> User.find(6)
  User Load (2.4ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 6]]
=> #<User id: 6, name: "mazlix", gold: 10, points: 10, next_click: "2000-01-01 00:00:00", created_at: "2012-05-23 23:40:39", updated_at: "2012-05-24 00:13:26">

u = User.find(6) u.next_click = Time.utc(2013)然后同样的事情发生u.save

irb(main):001:0> u = User.find(6)
  User Load (38.8ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 6]]
=> #<User id: 6, name: "mazlix", gold: 10, points: 10, next_click: "2000-01-01 00:00:00", created_at: "2012-05-23 23:40:39", updated_at: "2012-05-24 00:57:28">
irb(main):002:0> u.next_click = Time.utc(2013)
=> 2013-01-01 00:00:00 UTC
irb(main):003:0> u
=> #<User id: 6, name: "mazlix", gold: 10, points: 10, next_click: "2013-01-01 00:00:00", created_at: "2012-05-23 23:40:39", updated_at: "2012-05-24 00:57:28">
irb(main):004:0> u.save
   (10.9ms)  BEGIN
   (3.7ms)  UPDATE "users" SET "next_click" = '2013-01-01 00:00:00.000000', "updated_at" = '2012-05-24 03:05:46.059530' WHERE "users"."id" = 6
   (2.2ms)  COMMIT
=> true
irb(main):005:0> u
=> #<User id: 6, name: "mazlix", gold: 10, points: 10, next_click: "2013-01-01 00:00:00", created_at: "2012-05-23 23:40:39", updated_at: "2012-05-24 03:05:46">
irb(main):006:0> User.find(6)
  User Load (33.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 6]]
=> #<User id: 6, name: "mazlix", gold: 10, points: 10, next_click: "2000-01-01 00:00:00", created_at: "2012-05-23 23:40:39", updated_at: "2012-05-24 03:05:46">

app/models/user.rb:

class User < ActiveRecord::Base
  attr_accessible :gold, :name, :next_click, :points
end
4

2 回答 2

6

您已经创建了一个时间列。有点令人困惑的是,即使在 ruby​​ 中Time存储时间 + 日期,在数据库世界中,存在纯时间的概念(即只有几小时/分钟/秒),这就是当您添加一列类型 :time 到您的移民。

Ruby 本身没有代表没有日期的时间的类,因此 rails 使用了一个实例Time但忽略了日期位。

如果您想要一个同时存储时间和日期的列,请将列更改为 :datetime 列(Time在大多数情况下,您仍然会得到一个实例。

于 2012-05-28T07:29:03.130 回答
1

在您的 ActiveRecord 中可以使用数据类型:timestamp:datetime存储正确的日期格式。

于 2012-05-31T21:42:54.160 回答