I have send json response of a Rails AREL query result based on two tables. The response includes two timestamp columns: updated_at and updated_at_table_2. I override ActiveSupport::TimeWithZone.as_json method to obtain the desired datetime format for JSON. The same approach is shown at
http://stackoverflow.com/questions/2937740/rails-dates-with-json
My current JSON response is:
{
“updated_at”:”10/26/2012 22:04:07 -0400″,
“updated_at_table_2″:”2012-10-27 02:04:07.463015”
}
I want them to be the same. I relies below Rails code to produce json.
render :json => { :customer_order => @customer_order }
where @custoemr_order derived from:
CustomerOrder.select(%Q[
updated_at,
c.updated_at as updated_at_table_2
] ).
joins( %{ as co inner join customers as c on (co.customer_id = c.id)
Question: how can I tell Rails 3 to process as_json the same way for updated_at_table_2 as for updated_at column?
Any suggestions/pointers are great too.
Note: I found this post asking about the same root problem (though not about json) without good solution. :
http://stackoverflow.com/questions/12067173/rails-postgres-not-returning-timezone-info-on-column-from-joined-table
If you look at what your query gives you, you’ll see exactly where you’re going wrong:
ActiveRecord has no way of know what sort of thing
updated_at_table_2is supposed to be so it leaves it as a String and yourto_jsonmonkey patch won’t be applied to strings.If you want to keep using your
to_jsonmonkey patch (which I think is a bad idea), then you need to manually convertupdated_at_table_2to anActiveSupport::TimeWithZonewith something like this:Alternatively, you could load the associated object and call
updated_aton that.I’d scrap the whole approach though: let the server work exclusively in UTC, send the clients timestamps in an ISO-8601 format, and let the clients deal with applying the local timezone.