使用Rails和Mysql的毫秒数

使用Rails + Mysql时,以毫秒为单位存储时间的最佳方法是什么?

我将使用decimal和composed_of,以便能够将此值作为Ruby Time进行操作。 有没有人有更好的主意?!

我不确定我是否完全理解你要做的是什么,但你是否考虑过简单地覆盖模型中的读写器方法? 如果这适合您,那么它可能比您提出的解决方案更受欢迎,因为它可以说更具可读性。

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 

自问这个问题已经过去好几年了。 这是一个更新的解决方案:

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

发布了一个解决方案,使用composed_of在MySql中存储毫秒精度

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

1)将其存储为:十进制,具有足够的精度以满足您的需要。

2)自己创建一个帮助方法。 像这样的东西:

 # 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 

我的方法是:

打开时间类并实现方法:from_milis和: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 

将列从时间戳迁移到:decimal,:precision => 17

然后,在我使用此列作为属性的AR类中:

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

我在arel查询中使用此属性时只有gochas,我必须显式调用to_milis才能在比较中获得预期的值。