Home > Software design >  Rails active storage - Download link
Rails active storage - Download link

Time:12-08

I am trying to create a download link with active storage to download whatever files has been uploaded using the

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

But instead it's showing me undefined method filename for #<Order id: 1, paper_size: A4....

How can i fix this??

index.html.erb:

<div >Admin Dashboard</div>
<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>

According to the tutorials and documentation, it said we need to use the rails_blob_path function to create downloads but when I use it I am getting an error saying 'undefined method filename'.

I am trying to create a download link inside of a table when i use:

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

It works and redirects me to root path which indicates that f.files.attached? is returning TRUE, but when i call the rails_blob_path function its not working.

CodePudding user response:

You need to pass Active Storage instances to the rails_blob_path path (instead of the Active Record parent object). Since it seems you have multiple files, it should be something like (iterate through all "files" and create a link for each one):

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