ruby-on-rails 服务器日志中存在ActiveStorage::FileNotFoundError(ActiveStorage::FileNotFoundError),但在控制台中不可重现

g6baxovj  于 11个月前  发布在  Ruby
关注(0)|答案(3)|浏览(144)

我有以下模型:

class Section < ApplicationRecord
  has_many_attached :files
  def to_dir
    [client.to_dir, operation.to_dir, self.name.parameterize].join('/')
  end
  after_save :transload_files

  def transload_files
    TransloadService.sync( self.to_dir, self.files )
  end
end

字符串
transload_files方法是问题所在。下面是transload服务:

class TransloadService

    class << self

        def sync(check_dir, files)
            # First we have to check the transload dir for files that have been deleted on the app
            transloaded_files = Request.list(check_dir)
            cull_list = transloaded_files.reject{ |e| files.map{|t| t.filename }.include? Request.filename(e)}
            if cull_list.count > 0
                Request.trim(cull_list)
                p "#{cull_list.count} files trimed from #{check_dir}."
            end

            # Next we have to upload files which arent present in the transload dir

            send_list = files.reject{ |e| transloaded_files.map{|t| Request.filename(t) }.include? e.filename.to_s }
            if send_list.count > 0
                Request.upload_to(check_dir, send_list)
                p "#{send_list.map{|r| r.filename.to_s}.join(', ')} uploaded to #{check_dir}"
            end
        end

    end

end


下面是request.rb中的相关代码

class Request
    class << self
        def upload_to(destination, files)
            files.each do |file|
                send_to = connection.object("#{destination}/#{file.filename}")
                file.open{ |tmp| send_to.upload_file(tmp) }
            end
        end
    end
end


我面临的问题是:当after_save回调运行transload_files方法时,它返回ActiveStorage::FileNotFoundError (ActiveStorage::FileNotFoundError)
当我在控制台中运行Section.last.transload_files时,它完全按照预期执行。我在这里遗漏了什么?

cnwbcb6i

cnwbcb6i1#

经过大约两天的实验,我简单地得出结论,虽然创建了ActiveStorage记录,但它在任何模型回调中都不可用。官方AS文档在这里引用了after-create-commit回调,但是我无法像包含的示例那样调用blob.openblob.download。但是从控制台它可以工作。
我能够通过从Section模型调用作业,然后从作业调用transload服务来解决这个问题。

rjjhvcjd

rjjhvcjd2#

在我的例子中,我注意到的是,当在事务中使用ActiveStorage附加附件时,它不能正常工作。这适用于迁移或回调。

mftmpeh8

mftmpeh83#

我遇到了同样的问题,经过一些挖掘在互联网上这里是我发现的
1.正如@greyoxide指出的那样,官方文档中提到该文件仅在after_create_commit钩子中可用,而不在after_create中。
1.从这里开始,确定它只在after_create_commit钩子之前执行has_one_attached :filehas_many_attached :files时才能工作,为此,您可能必须更改模型中的行顺序,即

class Footer < ApplicationRecord
    after_create_commit :transload_files

    has_many_attached :files

字符串

相关问题