2011-11-05 65 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

相關問題