首页 > 解决方案 > 用户下载 ActiveStorage blob 附件时如何更新数据库?

问题描述

目前,用户可以使用以下链接在我的应用程序中下载 ActiveStorage blob:

link_to 'download', rails_blob_path(pj.document.file, disposition: 'attachment')

但是,我想更新数据库中的属性,以便在第一次下载文件时注册关联模型。该字段称为downloaded_at 字段。

我做了以下尝试:

  1. 在我更新模型时更改了 link_to > button_to。
  2. 添加了相应的路线
  3. 在数据库中添加以下代码:

    def download
        @proofreading_job = ProofreadingJob.find(params[:id])
        @proofreading_job.update(downloaded_at: Time.current) if current_user == @proofreading_job.proofreader.user
        response.headers["Content-Type"] = @proofreading_job.document.file.content_type
        response.headers["Content-Disposition"] = "attachment; #{@proofreading_job.document.file.filename.parameters}"
    
        @proofreading_job.document.file.download do |chunk|
          response.stream.write(chunk)
        end
        ensure
        response.stream.close
    end
    

但是,除了重定向到我不想要的 @proofreading_job 页面之外,这并没有做任何事情。

以前有没有人这样做过,如果是这样,我该如何完成这项任务。

标签: ruby-on-rails-5rails-activestorage

解决方案


我认为您也可以尝试使用您的动作控制器作为代理,概念是这样的:

  1. 在您的操作中下载文件
  2. 检查是否下载成功和其他验证
  3. 执行清理操作(在您的情况下,您的#3中添加的代码)
  4. 使用send_data/send_file渲染方法将文件发送回用户

例如在您的控制器中:

def download
  file = open(params[:uri])
  validate!
  cleanup!
  send_file file.path
end

那么在你看来:

link_to 'download', your_controller_path

以上只是概念,我很抱歉只提前提供伪代码。


推荐阅读