serialize date attributes

巧了我就是萌 提交于 2019-12-12 10:35:25

问题


I am using active_model_serializers and ember.js. One of my models has a date attribute. In rails date attributes are serialized in the format of "YYYY-MM-DD".

The problem; when ember-data de-serializes the date using the javascript Date constructor it assumes an "incorrect" timezone.

*Incorrect is not the best word but it is incorrect because I want it to default to the current timezone. DS.Model date attribute parses date (YYYY-MM-DD) incorrectly

I am thinking the active_model_serializer should take the date attribute and convert it to iso8601 format.

 Object.date.to_time_in_current_zone.iso8601

Is there a way to tell active_model_serializers how to serialize all date objects? Or should I be fixing the timezone issue in javascript?


回答1:


Here is my current solution but I really feel it should be possible to define how date objects get serialized globally.

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

My preferred solution now is to monkey patch the ActiveSupport::TimeWithZone.as_json method.

#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



回答2:


In the last version of ActiveSupport (4.2) Dates are under iso8601 format. You don't need anymore Monkey Patch. You can configure the output format

#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



来源:https://stackoverflow.com/questions/12538242/serialize-date-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!