序列化日期属性 [英] serialize date attributes
问题描述
问题;当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屋!