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": "[email protected]",
"first": "Test",
"last": "User"
}
請注意created_at如何以UTC出現,但「completed_at」是當地時間?任何想法爲什麼或如何讓他們成爲相同的格式?
你的問題只是不同的格式還是時區問題?如果它只是您可以使用的格式['DATE_FORMAT'](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format) –
我想我可以做到這一點。我想這似乎很奇怪,我必須。想知道爲什麼Rails會返回不同的格式... DATE_FORMAT也是特定於MySQL的,對吧? – jmccartie