Home > Net >  Rails Activestorage and sidekiq: Why is .attach not working with async job?
Rails Activestorage and sidekiq: Why is .attach not working with async job?

Time:11-07

I use this method in a sidekiq job:

  def attach_poster(poster_url,obj)
    resp = HTTParty.get(poster_url)
    file = Tempfile.new
    begin
      file.binmode
      file.write(resp.body)
      file.rewind
      obj.poster.attach(io: file, filename: "poster.png")
    ensure
      file.close
      file.unlink
    end
  end

This only works when I start the job with .perform_inline, like so: ImportJob.perform_inline(poster_url,obj) When I use .perform_async, the file does not get attached properly which results in a FileNotFoundError. Why is that?

I would like to use perform_async so that the job runs asynchronously from the main process.

I am on Ubuntu 20.04, latest versions of Rails and Sidekiq.

CodePudding user response:

I believe the issue here is that the job is enqueued before the file is fully uploaded hence you got the ActiveStorage::FileNotFound error.

I think this monkey patch will help you in this case. (I copied the code from the comment on github below to make it easier for you but the credit goes to the guy who commented on the issue).

There is also another stackoverflow question and it has been answered with the same solution -> here

Another question here asking how to make the ActiveStorage::Attached#attach function run synchronously -> here

Hope that helps, let me know if you have any other questions and I'd be more than happy to help.

module ActiveStorage::Blob::Analyzable
  def analyze_later
    analyze
  end
end
  • Related