robskrob
robskrob

Reputation: 2908

How to force ActiveStorage::Attached#attach to run synchronously -- disable async behavior

Is there anyway that I can force this method, ActiveStorage::Attached#attach to not enqueue a background job? In other words, I would like to disable the async behavior which seems to be included in ActiveStorage::Attached#attach so that the method executes synchronously and not asynchronously with either ActiveJob or something like Sidekiq

Upvotes: 11

Views: 2255

Answers (1)

Jacquen
Jacquen

Reputation: 1116

This seems to work currently:

def sync_attach(record, name, attachable)
  blob = ActiveStorage::Blob.create_and_upload!(
    io: attachable.open, filename: attachable.original_filename
  )
  blob.analyze
  attached = record.send(name)
  attached.purge
  attached.attach(blob)
end

# Given
class Thing < ActiveRecord::Base
  has_one_attached :image
end

# You can do
thing = Thing.create!
sync_attach(thing, :image, attachable)

You should also include mirroring in the method if you use that.

I welcome and seek any warnings, corrections, additions, etc. This is the best I've come up with so far.

Upvotes: 2

Related Questions