ruby-on-rails-5 - 用户下载 ActiveStorage blob 附件时如何更新数据库?
问题描述
目前,用户可以使用以下链接在我的应用程序中下载 ActiveStorage blob:
link_to 'download', rails_blob_path(pj.document.file, disposition: 'attachment')
但是,我想更新数据库中的属性,以便在第一次下载文件时注册关联模型。该字段称为downloaded_at 字段。
我做了以下尝试:
- 在我更新模型时更改了 link_to > button_to。
- 添加了相应的路线
在数据库中添加以下代码:
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 页面之外,这并没有做任何事情。
以前有没有人这样做过,如果是这样,我该如何完成这项任务。
解决方案
我认为您也可以尝试使用您的动作控制器作为代理,概念是这样的:
- 在您的操作中下载文件
- 检查是否下载成功和其他验证
- 执行清理操作(在您的情况下,您的#3中添加的代码)
- 使用send_data/send_file渲染方法将文件发送回用户
例如在您的控制器中:
def download
file = open(params[:uri])
validate!
cleanup!
send_file file.path
end
那么在你看来:
link_to 'download', your_controller_path
以上只是概念,我很抱歉只提前提供伪代码。
推荐阅读
- reporting-services - 在视觉工作室中缩进整个字段值
- python - 将 timedelta 值转换为浮点数
- elasticsearch - Elasticsearch 更新 ignore_above 给出非法参数异常
- javascript - JS Fetch - 无法从 BadRequest 响应中获取数据
- bash - 在一个管道中覆盖 bash 中的文件
- node.js - 在没有 docker-compose.yml 文件的单个 docker 文件中运行 react 和 node
- jasper-reports - 如何避免在 JasperReport 的最后一页打印页脚?
- javascript - JavaScript中如何计算数组的每个元素与其前一个元素的总和?
- .net - .net 的身份服务器 4 客户端模型
- node.js - _id 的 MongoDB $lookup 管道匹配不起作用