Fetch a Rails ActiveRecord 'datetime' attribute as a DateTime object

∥☆過路亽.° 提交于 2019-12-08 07:52:59

问题


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?


回答1:


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




回答2:


You can convert the Time Object very easy with Time::to_date or Time::to_datetime. For more information on this: http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Time/Conversions.html#M001125

so you should change your code like this:

myevent.ended_on.to_date
# or
myevent.ended_on.to_datetime


来源:https://stackoverflow.com/questions/2847688/fetch-a-rails-activerecord-datetime-attribute-as-a-datetime-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!