ActiveJob :: SerializationError-不支持的参数类型:时间/日期时间 [英] ActiveJob::SerializationError - Unsupported argument type: Time / DateTime
问题描述
我正在使用Rails 5和ActiveJob处理后台任务.我试图将使用 as_json
序列化的对象传递给我的工作,但出现以下错误:
I am using Rails 5 and ActiveJob to process background tasks. I am trying to pass a object serialized with as_json
to my job but I am receiving the following errors:
ActiveJob::SerializationError (Unsupported argument type: Time):
ActiveJob::SerializationError (Unsupported argument type: DateTime):
我知道ActiveJob不会接受Time/DateTime对象,因为某些排队系统不处理这些类型.因此,我要序列化的对象如下:
I understand that ActiveJob will not take Time/DateTime objects due to some queueing systems not handling those type. So the object I am trying to serialize is as follows:
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
The created_at, updated_at and due_date are all instances of ActiveSupport::TimeWithZone
我试图通过在初始化器中使用以下代码来覆盖此设置,我在另一篇SO帖子中找到了该代码,但这无济于事:
I have tried to override this by using the following code in a initializer, which I found in another SO post but it does not help:
class ActiveSupport::TimeWithZone
def as_json(options = {})
strftime('%Y-%m-%d %H:%M:%S')
end
end
在对象上运行 as_json
时,有人可以将日期作为字符串吗?
Could anyone help with possibly have the dates as strings when as_json
is run on the object?
推荐答案
请改用 card.to_json
.它将返回一个作业可以接受的JSON字符串.
Use card.to_json
instead. It will return a JSON string that the job will be able to accept.
如果您有逻辑要与 as_json
一起使用,只需将 to_json
链接到对 as_json
的调用的末尾,即 card.as_json.to_json
.
If you have logic you want to use with as_json
just chain to_json
to the end of the call to as_json
i.e. card.as_json.to_json
.
这篇关于ActiveJob :: SerializationError-不支持的参数类型:时间/日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!