Rails和Mysql的毫秒数 [英] Milliseconds with Rails and Mysql

查看:138
本文介绍了Rails和Mysql的毫秒数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the best way to store Time in milliseconds when using Rails+Mysql?

我将要使用十进制和composition_of,以便能够操作这个值作为Ruby时间。有没有人有更好的主意?

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?!

推荐答案

我的做法是:

打开时间类并实现方法:from_milis和:to_milis:

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

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

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

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

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

当我使用这个属性时,我刚刚有gochas,明确地调用to_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.

这篇关于Rails和Mysql的毫秒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆