Rails:从Query返回返回两种不同的时间戳格式

时间:2011-07-29 15:27:17

标签: ruby-on-rails activerecord

模型

scope :completed_at, select("(
      SELECT goals.created_at
      FROM goals
      WHERE goals.user_id = users.id
      ORDER BY goals.created_at
      LIMIT 1
    ) as completed_at
  ")

控制器

@users = User.select("email, first, last, created_at").completed_at.order("created_at ASC").limit(1).all

生成的SQL查询

SELECT email, first, last, created_at, (
 SELECT goals.created_at
 FROM goals
 WHERE goals.user_id = users.id
 ORDER BY goals.created_at
 LIMIT 1
 ) as completed_at
 FROM "users" ORDER BY created_at ASC LIMIT 5

示例JSON输出

"user": {
        "completed_at": "2011-06-07 15:04:56",
        "created_at": "2010-01-01T06:00:00Z",
        "email": "user@user.com",
        "first": "Test",
        "last": "User"
    }

注意created_at是如何以UTC形式出现的,但是“completed_at”是在当地时间出现的?知道为什么或如何让它们成为相同的格式?

1 个答案:

答案 0 :(得分:1)

Jon,我不确定你是如何生成json的,但是我会启动控制台,看看我是否能找出你为每一列获得的日期时间对象的类型。

另外,你在设置Time.zone吗?

rails c
> Time.zone = 'Central Time (US & Canada)'
> u = User.select("email, first, last, created_at").completed_at.first
> u.created_at.class
=> ActiveSupport::TimeWithZone
> u.completed_at.class
=> Time # (just a guess)

AR中处理时区转换的模块是here

有一点需要注意的是,AR不会TZ转换不在columns_hash中的任何列,即你的'completed_at'列不会被TZ转换。我知道,这似乎与你所经历的相反,但它可能会给你一个线索。