我需要将 api 返回的所有日期转换为 Unix 日期格式(秒)。单独来说很容易......
class ChimichangaSerializer < ActiveModel::Serializer
attributes :updated_at,
def updated_at
object.updated_at.to_i
end
end
但是由于我必须为所有事情做这件事,所以就会出现错误和疯狂。我怎样才能为所有这些实现此功能?
最佳答案
添加以下内容:
app/config/initializers/time_with_zone.rb
class ActiveSupport::TimeWithZone
def as_json(options = {})
to_i
end
end
这将覆盖所有时间戳转换为 json 时的默认行为。
关于ruby-on-rails - 事件模型序列化器将所有日期转换为秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42259660/