2013-05-10 79 views
0

如何使用日期時間值並使用HStore存儲和檢索它們?Rails Hstore dateTime saving

我使用這個:

module HstoreAccessor 
    def self.included(base) 
    base.extend(ClassMethods) 
    end 

    module ClassMethods 
    def hstore_accessor(hstore_attribute, *keys) 
     Array(keys).flatten.each do |key| 
     define_method("#{key}=") do |value| 
      send("#{hstore_attribute}=", (send(hstore_attribute) || {}).merge(key.to_s => value)) 
      send("#{hstore_attribute}_will_change!") 
     end 
     define_method(key) do 
      send(hstore_attribute) && send(hstore_attribute)[key.to_s] 
     end 
     end 
    end 
    end 
end 

ActiveRecord::Base.send(:include, HstoreAccessor) 

定義訪問器,它除了日期一切都很正常。當我將保存和檢索的模型的日期與尚未保存的模型的日期進行比較時,我在測試用例中得到了一些奇怪的東西。基本上保存之前的日期是一個「時間」類,然後是一個字符串。

我意識到hstore將東西保存爲字符串,但我很難搞清楚它如何序列化日期,所以我可以在字段的getter/setters中以相同方式反轉它。

任何幫助表示讚賞。謝謝。

回答

0

它看起來就像用「to_s」連載,所以反序列化回時刻Time#parse應該足夠

+0

我試過,但它也給了我的問題。我走的路是我把所有時間戳都保存爲iso8601字符串,並添加了一個驗證器來傳遞該格式。我的應用程序主要充當json API,因爲我使用客戶端的JavaScript爲用戶界面,所以它會做得很好。當我在數據庫中進行特定於日期的查詢時,我可能需要進行調整 – DArkO 2013-05-11 08:30:48