Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 310
robskrob Avatar asked Apr 19 '20 18:04

robskrob


People also ask

How do I delete active storage attachments?

To remove an attachment from a model, call purge on the attachment. If your application is set up to use Active Job, removal can be done in the background instead by calling purge_later . Purging deletes the blob and the file from the storage service.

How do I add an image to a model in Ruby on Rails?

Seeding Images in Your Rails Database Rails also enables users to seed the database with images if they want. To do so, you can use the 'attach' method, passing in a hash with two keys. The 'io' key calls the open method on the File class and takes the image's relative path as an argument.

How active storage works in Rails?

Active Storage uses two tables in your application's database named active_storage_blobs and active_storage_attachments . After creating a new application (or upgrading your application to Rails 5.2), run rails active_storage:install to generate a migration that creates these tables.


1 Answers

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.

like image 67
Jacquen Avatar answered Oct 21 '22 16:10

Jacquen