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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With