【问题标题】:Rails active storage - Download linkRails 主动存储 - 下载链接
【发布时间】:2022-12-08 01:44:41
【问题描述】:

我正在尝试创建一个带有活动存储的下载链接以下载已上传的任何文件 使用

<%= link_to 'download', rails_blob_path(f, disposition: "attachment") %>

但它显示给我undefined method filename for #&lt;Order id: 1, paper_size: A4....

我怎样才能解决这个问题??

索引.html.erb

<div class="h1">Admin Dashboard</div>



<table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">First</th>
      <th scope="col">Last</th>
      <th scope="col">Phone</th>
      <th scope="col">Email</th>
      <th scope="col">Size</th>
      <th scope="col">Color</th>
      <th scope="col">Type</th>
      <th scope="col">Quantity</th>
      <th scope="col">Description</th>
      <th scope="col">Downloads</th>
      
    </tr>
    
  </thead>

  <tbody>
    <% @orders.each do |f| %>
    <tr>
    
      <th scope="row"><%= f.id %></th>
      <td><%= f.first_name %></td>
      <td><%= f.last_name %></td>
      <td><%= f.phone_number %></td>
      <td><%= f.email %></td>
      <td><%= f.paper_size %></td>
      <td><%= f.color %></td>
      <td><%= f.paper_style %></td>
      <td><%= f.quantity %></td>
      <td><%= f.description %></td>

      <% if f.files.attached? %>
            <td><%= link_to 'download', rails_blob_path(f, disposition: "attachment") %></td>
      <% end %>

    <% end %>
    
    </tr>

  </tbody>

</table>

根据教程和文档,它说我们需要使用 rails_blob_path 函数来创建下载但是当我使用它时我收到一条错误消息“未定义的方法文件名”

我正在尝试在表格内创建下载链接

当我使用

<% if f.files.attached? %>
     <td><%= link_to 'download', root_url %></td>
<% end %>

它工作并将我重定向到根路径,这表明 f.files.attached? 正在返回 TRUE 但是当我调用 rails_blob_path 函数时它不起作用:(

【问题讨论】:

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


    【解决方案1】:

    您需要将 Active Storage 实例传递到 rails_blob_path 路径(而不是 Active Record 父对象)。由于您似乎有多个文件,因此它应该类似于(遍历所有“文件”并为每个文件创建一个链接):

    <% f.files.each do |file| %>
      <%= link_to 'download', rails_blob_path(file, disposition: "attachment") %></td>
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 2018-12-06
      • 2017-09-11
      • 1970-01-01
      • 1970-01-01
      • 2017-04-16
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 2021-07-25
      相关资源
      最近更新 更多