Johan
Johan

Reputation: 1917

Rails: created_at returns in different formats

I have a Song model which contains hundreds of thousands of songs, when I do queries using AR the time format (when rendered to json) is like this: 2011-12-19T11:04:39Z.

When I execute a query using Song.connection.execute() the time format returned when rendering to json is like this: 2011-11-20 19:00:08.207467

I actually prefer the raw format which is returned from the connection.execute() call. How can I make it so AR consistently does not convert it? How would I set the correct time zone etc?

I basically want to make sure its always in the same format when requests either through a raw db call and through AR.

Upvotes: 1

Views: 1305

Answers (3)

Marek Příhoda
Marek Příhoda

Reputation: 11198

I would go the other way: I would prefer the format that AR converts to/gives you for free. The reason is that it would then be much easier to configure the format (for that, see eg to_formatted_s).

For that to work, you'd have to avoid using connection.execute, and instead always use YourModel.find_by_sql - you would get an array of YourModel instances, with all the attributes correctly converted. For more info, see the docs: ri find_by_sql

Upvotes: 1

clyfe
clyfe

Reputation: 23770

Edit your locale files and set the date and time format as you wish

en:
  date:
    formats:
      default: "%Y-%m-%d %H:%M:%S.%Z"
      short: "%d %b"
      long: "%d %B %Y"

The syntax is that of strftime

Upvotes: 1

Amadan
Amadan

Reputation: 198324

The difference is likely due to the fact that ActiveRecord will create a Ruby DateTime, while execute would give you a plain string answer directly from the SQL engine. Thus, one is the default format from Rails, the other the default format from your DB.

This, or this might be relevant.

Upvotes: 0

Related Questions