Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azhao1981/ef62b53dad3058bbe5f1ca097bb9e319 to your computer and use it in GitHub Desktop.
Save azhao1981/ef62b53dad3058bbe5f1ca097bb9e319 to your computer and use it in GitHub Desktop.
ActiveRecord: Store Milliseconds (or Microseconds) in Timestamps/Datetimes with Rails / MySQL

ActiveRecord: Store Milliseconds (or Microseconds) in Timestamps with Rails / MySQL

Milliseconds in your Timestamps.

We got 'em, you want 'em.

Why

Shit needs to be PRECISE

LICENSE

MIT

class MillisecondsMigration < ActiveRecord::Migration
# Include non default date stamps here
# Key :table_name
# value [:column_names]
# NOTE: only MySQL 5.6.4 and above supports DATETIME's with more precision than a second.
TABLES_AND_COLUMNS = {
# Your :table_names here
}
STANDARD_ACTIVE_RECORD_COLUMNS = [:created_at, :updated_at]
TABLE_AND_COLUMNS.each {|k,v| v.concat(STANDARD_ACTIVE_RECORD_COLUMNS)}
def up
TABLE_AND_COLUMNS.each do |table, columns|
columns.each do |column|
# MySQL supports time precision down to microseconds -- DATETIME(6)
change_column table, column, :datetime, limit: 3
end
end
end
def down
TABLE_AND_COLUMNS.each do |table, columns|
columns.each do |column|
echange_column table, column, :datetime
end
end
end
end
# Save this in config/initializers/WHATEVER.rb
class Time
# Ruby will complain that it has already initialzed DATE_FORMATS because it has...
DATE_FORMATS = {
# Where 3N is the number of places after the decimal (.)
# If you want microseconds change 3N to 6N
:db => '%Y-%m-%d %H:%M:%S.%3N'
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment