Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 541
Arthur Avatar asked Nov 30 '16 17:11

Arthur


1 Answers

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.

like image 136
DiegoSalazar Avatar answered Oct 31 '22 22:10

DiegoSalazar