2

I have two rails models, MyParent and MyChild.

I'm trying to build a query using the rails .select() methods to efficiently extra a large number of rows for the database.

I want to pull back a number of columns from across the two tables, but when I reference a column which is of type datetime (or timestamp) but not in the original model, it is returned as a string.

Eg:

irb(main)> MyChild.select(['created_at as child_date', 'created_at']).first.child_date.class
=> String #Bad!!!
irb(main)> MyChild.select(['created_at as child_date', 'created_at']).first.created_at.class
=> ActiveSupport::TimeWithZone  #YAY!!!!

I first encountered this problem when attempted to pull a datetime from the MyParent table using joins().

How can I tell rails that I want child_date as a ActiveSupport::TimeWithZone object?

I'm using the latest version of Rails 3.2.

3
  • Can't you do that? CAST(child_date AS DATE) Commented May 7, 2013 at 19:08
  • 1
    It already is a date though. The problem seems to be that Rails can't figure out how to convert the sql result without info from ActiveRecord. Commented May 7, 2013 at 19:14
  • It still returns string. Commented May 8, 2013 at 8:48

1 Answer 1

1

The only solution that I could come up with was to cast the resulting date back into a TimeWithZone object

Time.zone.parse(MyChild.select(['created_at as child_date']).first.child_date)
# returns a ActiveSupport::TimeWithZone object
Sign up to request clarification or add additional context in comments.

Comments

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.