2012-09-21 130 views
7

我正在使用active_model_serializers和ember.js。我的一個模型有一個日期屬性。在軌道中,日期屬性以「YYYY-MM-DD」的格式序列化。序列化日期屬性

問題;當ember-data使用javascript Date構造函數對日期進行反序列化時,它會假定「不正確」的時區。

*錯誤不是最好的單詞,但它不正確,因爲我希望它默認爲當前時區。 DS.Model date attribute parses date (YYYY-MM-DD) incorrectly

我在想active_model_serializer應該採用日期屬性並將其轉換爲iso8601格式。

Object.date.to_time_in_current_zone.iso8601 

有沒有辦法告訴active_model_serializers如何序列化所有的日期對象?或者我應該在JavaScript中解決時區問題?

回答

7

這是我目前的解決方案,但我真的覺得應該可以定義日期對象如何全局序列化。

class InvoiceSerializer < ActiveModel::Serializer 
    attributes :id, :customer_id, :balance 

    def attributes 
    hash = super 
    hash['date'] = object.date.to_time_in_current_zone.iso8601 if object.date 
    hash 
    end 
end 

UPDATE

我首選的方案現在是猴子修補ActiveSupport::TimeWithZone.as_json方法。

#config/initializers/time.rb 
module ActiveSupport 
    class TimeWithZone 
    def as_json(options = nil) 
     time.iso8601 
    end 
    end 
end 

class InvoiceSerializer < ActiveModel::Serializer 
    attributes :id, :customer_id, :balance, :date 
end 
+1

您還可以添加任意的屬性:'屬性:id,:CUSTOMER_ID,:平衡:date'然後只需執行'高清date'而不是搞亂與整個屬性散列。 – awendt

1

在最新版本的ActiveSupport(4.2)中,日期採用iso8601格式。你不需要猴子補丁。您可配置輸出格式

#config/initializers/time.rb 
ActiveSupport::JSON::Encoding.use_standard_json_time_format = true # iso8601 format 
ActiveSupport::JSON::Encoding.time_precision = 3 # for millisecondes 

See the doc