1

I am trying to pass the view_context object to a background worker:

invoices = current_user.invoices
ArchiveInvoicesJob.perform_later(invoices.pluck(:id), view_context)

I understand that I cannot pass ActiveRecord:Relations to ActiveJob. That's why I'm passing the IDs instead.

But when I try to pass the view_context I get an ActiveJob::SerializationError.

The problem is that I need the view_context inside my Prawn PDF class to generate a bunch of PDFs.

How do I get it in there?

Tintin81
  • 9,821
  • 20
  • 85
  • 178
  • You should be able to open up a new view context inside your background job. You probably don't need to pass it as an argument. – max pleaner Jan 21 '20 at 18:16
  • @maxpleaner: OK, I just wonder how to do that? – Tintin81 Jan 21 '20 at 19:38
  • Have you tried to just call `view_context ` from the background job? I think `view_context` is just a way to access methods from the view layer - not something you have to 'pass around'. But I could be mistaken. – max pleaner Jan 21 '20 at 19:46
  • you can use `ApplicationController.render 'posts/index', assigns: { posts: Post.all }` [doc](https://api.rubyonrails.org/classes/ActionController/Renderer.html) – PGill Jan 21 '20 at 19:55
  • 1
    @maxpleaner the view_context is tied to the request so it does not exist outside of that context. Some helpers can be used of that outside that context and some can't. An example of this is `link_to` which fills in a lot of blanks from the current request. – max Jan 21 '20 at 20:31
  • 1
    You cant pass the entire view context to a background job as its a really complex and big object with references to the request, the controller, any assigns (instance variables of the controller) locals etc. Which means that its a nightmare to serialize. ActiveJob only serializes simple objects. – max Jan 21 '20 at 20:41

0 Answers0