Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callback for Active Storage file upload

Is there a callback for active storage files on a model

after_update or after_save is getting called when a field on the model is changed. However when you update (or rather upload a new file) no callback seems to be called?

context:

class Person < ApplicationRecord
  #name :string
  has_one_attached :id_document

  after_update :call_some_service

  def call_some_service
    #do something
  end
end

When a new id_document is uploaded after_update is not called however when the name of the person is changed the after_update callback is executed

like image 722
Toma Avatar asked Nov 09 '18 13:11

Toma


People also ask

Where are active storage files stored?

By default in the development environment, Active Storage stores all uploaded images on your local disk in the storage subdirectory of the Rails application directory. That's the file you uploaded!

How does active storage work?

Active Storage facilitates uploading files to a cloud storage service like Amazon S3, Google Cloud Storage, or Microsoft Azure Storage and attaching those files to Active Record objects.

How does active storage work 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.


2 Answers

For now, it seems like there is no callback for this case.

What you could do is create a model to handle the creation of an active storage attachment which is what is created when you attach a file to your person model.

So create a new model

class ActiveStorageAttachment < ActiveRecord::Base
  after_update :after_update

  private
  def after_update
    if record_type == 'Person'
      record.do_something
    end
  end
end

You normally have created the model table already in your database so no need for a migration, just create this model

like image 110
Uelb Avatar answered Sep 28 '22 10:09

Uelb


Erm i would just comment but since this is not possible without rep..

Uelb's answer works but you need to fix the error in comments and add it as an initializer instead of model. Eg:

require 'active_storage/attachment'

class ActiveStorage::Attachment
  before_save :do_something

  def do_something
    puts 'yeah!'
  end
end
like image 23
Premysl Donat Avatar answered Sep 28 '22 10:09

Premysl Donat