序列化日期属性 [英] serialize date attributes

查看:183
本文介绍了序列化日期属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用active_model_serializers和ember.js。我的一个模型有一个日期属性。在rails日期属性按YYYY-MM-DD的格式进行序列化。



问题;当ember数据使用javascript Date构造函数取消序列化日期时,它假定不正确的时区。



*不正确不是最好的单词,但它是不正确的,因为我希望它默认为当前时区。 DS.Model date属性解析日期(YYYY-MM- DD)不正确



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

  Object.date.to_time_in_current_zone.iso8601 

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

解决方案

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

  class InvoiceSerializer< ActiveModel :: Serializer 
属性:id,:customer_id,:balance

定义属性
哈希=超级
哈希['日期'] = object.date.to_time_in_current_zone .iso8601如果object.date
哈希
结束
结束

更新



我现在的首选解决方案是将猴子补丁到$ code> ActiveSupport :: TimeWithZone.as_json 方法。

 #config / initializers / time.rb 
模块ActiveSupport
类TimeWithZone
def as_json(options = nil )
time.iso8601
end
end
end

class InvoiceSerializer< ActiveModel :: Serializer
属性:id,:customer_id,:balance,:date
end


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?

解决方案

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

这篇关于序列化日期属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆