用户下载ActiveStorage Blob附件时如何更新数据库?

che*_*ell 5 ruby-on-rails-5 rails-activestorage

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

link_to 'download', rails_blob_path(pj.document.file, disposition: 'attachment')
Run Code Online (Sandbox Code Playgroud)

但是,我想更新数据库中的属性,以便相关模型在首次下载文件时进行注册。该字段称为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
    
    Run Code Online (Sandbox Code Playgroud)

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

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

che*_*ell 0

最后我只是使用了一些javascript来捕获按钮的点击,如下所示:

    td = link_to rails_blob_path(pj.document.file, disposition: 'attachment'), 
         id: pj.document.id, 
   download: pj.document.file_name, 
      class: "btn btn-outline-secondary btn-sm btn-download" do
        =pj.document.file_name 
        i.fa.fa-download.ml-3 aria-hidden="true"
Run Code Online (Sandbox Code Playgroud)

咖啡脚本:

  $('.btn-download').on 'click', (e) ->
    id = $(this).attr('id')
    $.ajax {url: Routes.document_path(id), type: 'PUT'}
Run Code Online (Sandbox Code Playgroud)

路线.rb

resources :documents, only: [:show, :update]
Run Code Online (Sandbox Code Playgroud)

文件_控制器.rb:

  def update
    document = Document.find(params[:id])
    authorize([:proofreaders, document]) 
    document.update(downloaded_at: Time.current) if document.downloaded_at.nil?
    head :ok
  end
Run Code Online (Sandbox Code Playgroud)

这看起来效果很好。它更新数据库并且用户将文件下载到他们的计算机上。