开发者

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

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 F开发者_StackOverflow中文版lotilla 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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜