【问题标题】:serialize date attributes序列化日期属性
【发布时间】:2012-09-21 21:14:00
【问题描述】:

我正在使用 active_model_serializers 和 ember.js。我的一个模型有一个日期属性。在 Rails 中,日期属性以“YYYY-MM-DD”的格式序列化。

问题;当 ember-data 使用 javascript Date 构造函数反序列化日期时,它假定一个“不正确的”时区。

*不正确不是最好的词,但它是不正确的,因为我希望它默认为当前时区。 DS.Model date attribute parses date (YYYY-MM-DD) incorrectly

我认为 active_model_serializer 应该采用 date 属性并将其转换为 iso8601 格式。

 Object.date.to_time_in_current_zone.iso8601

有没有办法告诉 active_model_serializers 如何序列化所有日期对象?还是我应该在 javascript 中修复时区问题?

【问题讨论】:

    标签: ember.js ember-data active-model-serializers


    【解决方案1】:

    这是我目前的解决方案,但我真的觉得应该可以定义日期对象如何全局序列化。

    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
    

    更新

    我现在首选的解决方案是猴子修补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
    

    【讨论】:

    • 您还可以添加任意属性:attributes :id, :customer_id, :balance, :date,然后只需实现def date,而不是弄乱整个属性哈希。
    【解决方案2】:

    在 ActiveSupport (4.2) 的最新版本中,日期采用 iso8601 格式。您不再需要 Monkey Patch。可以配置输出格式

    #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

    【讨论】:

      猜你喜欢
      • 2018-12-13
      • 2021-08-09
      • 2019-05-01
      • 2016-05-26
      • 1970-01-01
      • 1970-01-01
      • 2011-04-03
      相关资源
      最近更新 更多