Question: ActiveJob::SerializationError - Unsupported argument type: Time / DateTime

Question

ActiveJob::SerializationError - Unsupported argument type: Time / DateTime

Answers 1
Added at 2016-11-30 18:11
Tags
Question

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):

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>

When I run:

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}

The created_at, updated_at and due_date are all instances of ActiveSupport::TimeWithZone

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

Could anyone help with possibly have the dates as strings when as_json is run on the object?

Any help would be appreciated!

Thanks

Answers to

ActiveJob::SerializationError - Unsupported argument type: Time / DateTime

nr: #1 dodano: 2016-11-30 20:11

Use card.to_json instead. It will return a JSON string that the job will be able to accept.

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.

Source Show
◀ Wstecz