开发者

Milliseconds with Rails and Mysql

What 开发者_JS百科is the best way to store Time in milliseconds when using Rails+Mysql?

I am about to use a decimal and composed_of in order to be able to manipulate this value as a Ruby Time. Does anyone have a better idea?!


Several years have passed since this was asked. Here's an updated solution:

https://gist.github.com/MarkMurphy/93adca601b05acffb8b5601df09f66df


I'm not sure I fully understand what you're trying to do, but have you considered simply overriding the reader/writer methods in your model?. If this works for you, it might be preferred over your proposed solution since it's arguably more readable.

MyClass < ActiveRecord::Base

  # Override reader method
  def my_attribute
    super().from_milis
  end

  # Override writer method
  def my_attribute=(value)
    super(value.to_milis)
  end

end


Posted a solution to store millisecond precision in MySql using composed_of

http://ternarylabs.com/2011/09/26/millisecond-precision-timestamp-in-rails-with-mysql/


1) Store it as a :decimal with ample precision for your purposes.

2) Create a helper method yourself. Something like this:

# app/helpers/application_helper.rb
module ApplicationHelper
  def time_with_ms(time)
    minutes = (time % 1.minute).floor
    seconds = time % 1.minute
    "%02d:%05.2f" % [minutes, seconds]
  end
end


My approach was to:

open the time class and implement the methods :from_milis and :to_milis :

class Time
  def self.from_milis(milis)
    self.at(milis.to_f/1000)
  end

  def to_milis
    self.to_f*1000
  end
end

migrate the column from timestamp to :decimal,:precision=>17

then, in the AR class in which i am using this column as attribute:

composed_of :ts,
    :class_name=>"Time",
    :mapping=>%w(ts to_milis),
    :constructor=>:from_milis,
    :converter=>:from_milis

I just had gochas when using this attribute in arel queries, where I had to explicitly call to_milis in order to get the intended value in the comparision.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜