Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: always include the milliseconds with created_at for every model

How do I modify my Rails app to always include the milliseconds information with the created_at field of my models?

This question has the answer for how to do it for an individual model, but I want to do it globally.


For example, when I retrieve all my Item models (by hitting /items with a GET), I get the following JSON:

[{"created_at":"2011-08-07T23:42:15Z","updated_at":"2011-08-07T23:42:15Z","id":180,"user_id":6,"content":"test"}]

But note that the created_at field doesn't have any information about the millisecond that it was created. How do I include that for all my models?

like image 501
Chetan Avatar asked Aug 07 '11 23:08

Chetan


1 Answers

For Rails 4.1 and above you can set the time_precision, e.g. in application.rb

ActiveSupport::JSON::Encoding.time_precision = 3

By the way, showing the milliseconds is now the default, it can be set to 0 if they should be omitted. Also it's good to know that .iso8601 doesn't include milliseconds but .as_json preserves them.

like image 66
einSelbst Avatar answered Sep 21 '22 20:09

einSelbst