取一个Rails的ActiveRecord“日期时间”属性作为DateTime对象 [英] Fetch a Rails ActiveRecord 'datetime' attribute as a DateTime object
问题描述
我在我的模型,其中包含一个日期/时间值之一的属性,并使用 t.datetime声明:ended_on
在我的迁移
I have an attribute in one of my models that contains a Date/Time value, and is declared using t.datetime :ended_on
in my migrations.
当我取使用这个值 myevent.ended_on
,我收到了时间
对象。问题是,当我尝试使用这个属性作为轴线的舰队的图表,这是行不通的正常,因为舰队只能识别日期为日期
或的DateTime
的对象。
When I fetch this value using myevent.ended_on
, I get a Time
object. The problem is that when I try to use this attribute as an axis in a Flotilla chart, it doesn't work properly because Flotilla only recognizes dates as Date
or DateTime
objects.
我想过写一个虚拟属性,将现有的时间值转换为DateTime,但我警惕这样做的,因为我听说,时间不能超过2040后处理日期,和我不'牛逼想冒险创造一个2040错误后话了担心。
I thought about writing a virtual attribute that will convert the existing Time value to a DateTime, but I'm wary of doing this, since I've heard that Time can't handle dates later than 2040, and I don't wish to risk creating a "2040 bug" to worry about later.
有没有什么办法可以说服的ActiveRecord返回datetime对象为这个属性,而不是时间的物体?
Is there any way I can persuade ActiveRecord to return DateTime objects for this attribute instead of Time objects?
推荐答案
您可以随时创建一个方法来重写属性,如下:
You can always create a method to override the attribute, as follows:
class YourModel
....
def ended_on
self['ended_on'].to_datetime # if you need date object use to_date instead
end
....
end
希望帮助
这篇关于取一个Rails的ActiveRecord“日期时间”属性作为DateTime对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!