【问题标题】:How to display Active Storage attached file when editing form?编辑表单时如何显示 Active Storage 附件?
【发布时间】:2020-03-17 18:58:16
【问题描述】:

我正在构建一个协议管理应用。每个协议都有供应商、激活、到期日期和文件。文件是 pdf 格式的附加协议。我使用 Active Storage 来附加文件。当我编辑表格时,我看不到附件。因此,如果我更改任何其他参数,比如说供应商并更新协议,则先前附加的文件将被删除。

Editing Agreement form

如果我在编辑时不上传任何其他文件,我应该怎么做才能使附加的文件名在更新时出现而不被删除?

更新:

这里是代码。除了将 :file 添加到允许的参数之外,我没有对生成的协议控制器进行任何调整。

agreement.rb

class Agreement < ApplicationRecord
  belongs_to :vendor
  has_one_attached :file  
end


agreements_controller.rb

class AgreementsController < ApplicationController
  def agreement_params
    params.require(:agreement).permit(:vendor_id, :activation_date, :expiration_date, :file)
  end
end


_form.html.erb

<%= form_with(model: agreement, local: true) do |form| %>
…
<div class="field">
    <%= form.label :file %>
    <%= form.file_field :file %>
 </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

【问题讨论】:

  • 请给我们一些代码
  • 问题不在于文件没有显示,问题在于即使参数为空,您也在更新附件。您必须显示一些代码(编辑和更新操作,至少编辑表单)
  • 感谢您的解释,我发现如果协议参数包含更新时的新附件,我必须检查协议控制器.rb。如果没有,我应该使用以前附加的文件。我已将该行添加到更新函数中:agreement_params[:file] = @agreement.file unless @agreement.file.attached?我在编辑时仍然看不到之前附加的文件名,但如果我不上传新文件,至少它不会被删除

标签: ruby-on-rails rails-activestorage


【解决方案1】:

在协议模型中添加

attribute :remove_file, :boolean,  default: false
after_save :purge_file, if: :remove_file

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多