序列化日期属性

时间:2012-09-21 21:14:00

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

我正在使用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中修复时区问题吗?

2 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分: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