2011-11-05 50 views
1

我只花了相当多的时间来试图解决这个问题,虽然我确实修复了它(有点)我是不知道发生了什么。Rails 3.1,Ruby 1.9.2,Mongoid 2.3.3 - poltergeist在我的日期时间

乘坐Mongoid模型:

class Game 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    field :start, type: DateTime 
    index :start 

    def process(attrs = nil, role = :default, guard_protected_attributes = true) 
    if attrs.keys.include?('start(1i)') 
     now = DateTime.now 
     year = attrs.delete('start(1i)').to_i || now.year 
     month = attrs.delete('start(2i)').to_i || now.month 
     day = attrs.delete('start(3i)').to_i || now.day 
     hour = attrs.delete('start(4i)').to_i || now.hour 
     min = attrs.delete('start(5i)').to_i || now.minute 
     sec = attrs.delete('start(6i)').to_i || 0 # seconds 
     zone = attrs.delete('start(7i)').to_i || 0 # UTC 

     # I'm not sure what is happening here, but we need to adjust the hour 
     # otherwise Rails/Mongoid will mangle the time... 
     start = DateTime.new(year, month, day, hour, min, sec, zone) 
     # First we set the time and self.start will be wrong by 6 hours (my timezone) 
     self.start = start 
     # We do this and the time will change by several hours!!! 
     self.start -= 0.seconds 
     # Can't make a simple substraction as we'll get a Rational? The WTFs just keep piling up... 
     diff = (self.start.to_i - start.to_i).seconds 
     self.start -= diff 
     self.start -= diff # Yeah, twice? 
    end 

    super(attrs, role, guard_protected_attributes) 
    end 
end 

为什么process方法?那么,我不能让start属性由Mongoid::MultiParameterAttributes来处理,因为“某些东西”会通过使用我的本地时区对其进行调整(“还没弄清楚哪个辉煌的代码正在这样做”)来“修复”它。

在该代码中,start变量将始终具有正确的时间,但正如您所看到的,self.start必须用木槌击打,直到时间正确。

奇怪吗?人不让我开始。这与Rails多参数属性有关,它允许我使用多个select标签来设置日期/时间(start(1i)的东西)。

Time.zone是UTC,所以我不知道为什么它使用我的本地时区来破坏时间。

但最奇怪的东西是为什么我做这么多的调整...

我不期待尽快找到一个真正的解决方案随时随地,但我想知道你的想法。

PS:Awww,SO没有让我添加poltergeist标签。

回答

0

原来我刚:

Mongoid::Config.use_utc = true 
Mongoid::Config.use_activesupport_time_zone = true 

这仍然没有解释的怪异行为做。或者它可以,我没有看到它:)

+0

use_utc should = false 按照https://github.com/mongoid/mongoid/issues/1475&& https://github.com/mongoid/mongoid/issues/878 – GoodGets

+0

此外,该字段应该是一个“时间”对象而不是“日期时间”,以便它能够正常工作 – GoodGets

相关问题