我正在使用Rails 5和ActiveJob来处理后台任务。我正在尝试将使用as_json
序列化的对象传递给我的工作,但我收到以下错误:
ActiveJob::SerializationError (Unsupported argument type: Time):
ActiveJob::SerializationError (Unsupported argument type: DateTime):
据我所知,由于某些排队系统没有处理这些类型,ActiveJob不会占用Time / DateTime对象。所以我试图序列化的对象如下:
card = Card.first
=> #<Card id: 256, title: "quis", description: "Sunt corporis error laudantium veritatis impedit r...", due_date: "2016-12-15 12:00:00", slug: "quis", created_at: "2016-11-30 17:00:01", updated_at: "2016-11-30 17:00:01", list_id: 26, position: 0, period_type: "hours", period_length: 0.0, user_id: 1>
当我跑步时:
card.as_json
=> {"id"=>256, "title"=>"quis", "description"=>"Sunt corporis error laudantium veritatis impedit repellat quasi.", "due_date"=>Wed, 15 Dec 2016 12:00:00 UTC +00:00, "slug"=>"quis", "created_at"=>Wed, 30 Nov 2016 17:00:01 UTC +00:00, "updated_at"=>Wed, 30 Nov 2016 17:00:01 UTC +00:00, "list_id"=>26, "position"=>0, "period_type"=>"hours", "period_length"=>0.0, "user_id"=>1}
created_at,updated_at和due_date都是ActiveSupport::TimeWithZone
我试图通过在初始化程序中使用以下代码来覆盖它,我在另一篇SO帖子中找到了它,但它没有帮助:
class ActiveSupport::TimeWithZone
def as_json(options = {})
strftime('%Y-%m-%d %H:%M:%S')
end
end
在对象上运行as_json
时,是否有人可以帮助将日期作为字符串?
答案 0 :(得分:10)
请改用card.to_json
。它将返回作业能够接受的JSON字符串。
如果您有逻辑,则只需将as_json
链接to_json
链接到as_json
card.as_json.to_json
的调用结束即可。