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?
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.
Overriding ActiveSupport::TimeWithZone#as_json
worked for me:
class ActiveSupport::TimeWithZone
def as_json(options = nil)
if ActiveSupport::JSON::Encoding.use_standard_json_time_format
xmlschema(3)
else
%(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
end
end
end
Make sure to put this code in a file that is required by your Rails app. Now when I convert a created_at attribute to JSON, I get the milliseconds:
puts Post.last.created_at.to_json
# => "2012-06-29T11:51:00.841Z"
Also make sure to use Time.zone
to instantiate new Time objects so that they show the same JSON behavior:
time = Time.zone.now
puts time.to_json
# => "2012-06-29T16:45:30.547Z"
Hope this helps someone!
I was able to override the created_at
attribute selector for my Item model using this guide.
Anyone know how to do it for all models?