1

Model

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
  ")

Controller

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

Resulting SQL Query

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

Sample JSON Output

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

Note how created_at is coming out as UTC, but "completed_at" is coming out local time? Any idea why or how to get them to be the same format?

2
  • Is your problem just the different formats or is it a timezone issue? If it's just the format you can use DATE_FORMAT Commented Jul 29, 2011 at 15:34
  • I supposed I could do that. I guess it just seems weird to me to have to. Wondering why Rails is returning different formats... DATE_FORMAT is also MySQL-specific, right? Commented Jul 29, 2011 at 15:42

1 Answer 1

1

Jon, I'm not sure exactly how you're generating the json, but I'd fire up the console and see if I could figure out what type of datetime object you're getting for each column.

Also, are you setting 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)

The module in AR that handles time zone conversion is here.

One thing to note is that AR will not TZ convert any columns not in the columns_hash, i.e. your 'completed_at' column will NOT get TZ converted. I know, this seems backwards from what you're experiencing, but it may give you a clue.

Sign up to request clarification or add additional context in comments.

2 Comments

> u.completed_at.class => String # sadTrombone I guess I'll just run in_time_zone('UTC') to convert to TimeWithZone
Jon, I think this SO question is the same issue -- looks like AR won't convert the the timestamp out of postgres because it doesn't know it's a timestamp. stackoverflow.com/questions/5737504/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.