获取Rails ActiveRecord'datetime'属性作为DateTime对象 [英] Fetch a Rails ActiveRecord 'datetime' attribute as a DateTime object
问题描述
t.datetime:ended_on
声明。 当我使用 myevent.ended_on
获取这个值时,我得到一个时间
对象。问题是,当我尝试在 Flotilla 图表中将此属性用作轴时,它不会工作正常,因为Flotilla只识别日期为 Date
或 DateTime
对象。
$ b $我想过写一个虚拟属性,将现有的Time值转换为DateTime,但是我很担心这样做,因为我听说Time不能在2040年以后才能处理日期,不要冒险创造一个2040错误,以后担心。
有没有办法我可以说服ActiveRecord返回此属性的DateTime对象而不是Time对象
您可以随时创建一个覆盖属性的方法,如下所示:
class YourModel
....
def ends_on
self ['ended_on'] to_datetime #如果你需要日期对象使用to_date而不是
结束
....
end
希望有帮助
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.
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.
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.
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
Hopefully that helps
这篇关于获取Rails ActiveRecord'datetime'属性作为DateTime对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!