Active Storage 文件上传回调

Callback for Active Storage file upload

是否有模型上活动存储文件的回调

after_updateafter_save 在模型上的字段更改时被调用。但是,当您更新(或者更确切地说是上传新文件)时,似乎没有回调被调用?

上下文:

class Person < ApplicationRecord
  #name :string
  has_one_attached :id_document

  after_update :call_some_service

  def call_some_service
    #do something
  end
end

上传新的 id_documentafter_update 不会被调用,但是当人的 name 发生变化时,会执行 after_update 回调

目前,似乎没有针对此案例的回调。

您可以做的是创建一个模型来处理活动存储附件的创建,这是在您将文件附加到个人模型时创建的。

所以创建一个新模型

class ActiveStorageAttachment < ActiveRecord::Base
  after_update :after_update

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

您通常已经在数据库中创建了模型 table,因此无需迁移,只需创建此模型

呃,我只是想发表评论,但因为没有代表这是不可能的..

Uelb 的答案有效,但您需要修复注释中的错误并将其添加为初始值设定项而不是模型。例如:

require 'active_storage/attachment'

class ActiveStorage::Attachment
  before_save :do_something

  def do_something
    puts 'yeah!'
  end
end

@Uleb 的回答让我完成了 90%,但为了完成,我将 post 我的最终解决方案。

我遇到的问题是我无法对 class 进行猴子修补(不知道为什么,即使按照 @user10692737 要求 class 也无济于事)

所以我复制了源码(https://github.com/rails/rails/blob/fc5dd0b85189811062c85520fd70de8389b55aeb/activestorage/app/models/active_storage/attachment.rb#L20)

并修改它以包含回调

require "active_support/core_ext/module/delegation"

# Attachments associate records with blobs. Usually that's a one record-many blobs relationship,
# but it is possible to associate many different records with the same blob. If you're doing that,
# you'll want to declare with <tt>has_one/many_attached :thingy, dependent: false</tt>, so that destroying
# any one record won't destroy the blob as well. (Then you'll need to do your own garbage collecting, though).
class ActiveStorage::Attachment < ActiveRecord::Base
  self.table_name = "active_storage_attachments"

  belongs_to :record, polymorphic: true, touch: true
  belongs_to :blob, class_name: "ActiveStorage::Blob"

  delegate_missing_to :blob

  #CUSTOMIZED AT THE END:
  after_create_commit :analyze_blob_later, :identify_blob, :do_something

  # Synchronously purges the blob (deletes it from the configured service) and destroys the attachment.
  def purge
    blob.purge
    destroy
  end

  # Destroys the attachment and asynchronously purges the blob (deletes it from the configured service).
  def purge_later
    blob.purge_later
    destroy
  end


  private
    def identify_blob
      blob.identify
    end

    def analyze_blob_later
      blob.analyze_later unless blob.analyzed?
    end

    #CUSTOMIZED:
    def do_something

    end
end

不确定这是最好的方法,如果我找到更好的解决方案会更新

在我的案例中,跟踪附件时间戳有效

class Person < ApplicationRecord
  has_one_attached :id_document

  after_save do    
    if id_document.attached? && (Time.now  - id_document.attachment.created_at)<5
      Rails.logger.info "id_document change detected"
    end
  end
end

我所做的是在我的记录中添加回调:

after_touch :check_after_touch_data

如果添加、编辑或删除 ActiveStorage 对象,则会调用此方法。我使用此回调来检查是否发生了变化。