Rails Read csv file data with active storage
Asked Answered
T

3

22

I have this class and I am using active storage

class MaterialsUpload < ApplicationRecord
  has_one_attached :csv_file
end

This is the attachment

#<ActiveStorage::Attached::One:0x007ff1f0be9e90
 @dependent=:purge_later,
 @name="csv_file",
 @record=
  #<MaterialsUpload:0x007ff1f0c604f0
   id: 3,
   success: 0,
   errors_list: [],
   total: 0,
   created_at: Mon, 12 Feb 2018 14:43:35 UTC +00:00,
   updated_at: Mon, 12 Feb 2018 14:43:35 UTC +00:00>>

Is there a way I can read the data so I can do something like this

string = materials_upload.csv_file.read
CSV.parse(csv_string, headers: true) do |row|
    # do something
end
Thevenot answered 12/2, 2018 at 15:23 Comment(0)
R
39

Use download to obtain the file’s contents:

CSV.parse(materials_upload.csv_file.download, headers: true) do |row|
  # ...
end
Resolute answered 13/2, 2018 at 16:9 Comment(2)
Thanks that was what a was looking for !!Thevenot
@george-claghorn I need to use CSV.foreach instead of CSV.parse (because there are too many rows in the file) and file.download seems like using too much memory. How can I get a needed file path? (I'm using amazon S3)Closet
C
1

I think this could be another option (when it's local on disk). I used code from this answer

file_path = ActiveStorage::Blob.service.send(:path_for, materials_upload.csv_file.key)
CSV.foreach file_path, headers: true do
  # ...
end
Closet answered 20/9, 2018 at 18:57 Comment(0)
W
-3

After uploading you can read CSV file into an HTML table with CSV::Table lib:

def show
  @csv_data = CSV.open('uploaded_file.csv', headers: true).read
end

Example for view:

<table cellspacing="5" cellpadding="5" border="0" >
  <tr>
  <% @csv_data.headers.each do |header| %>
    <th><%= header %></th>
  <% end %> 
  </tr>
  <% @csv_data.each do |row| %>
    <tr>
    <% row.each do |value| %>
      <td><%= value[1] %></td>
    <% end %>
    </tr>
  <% end %> 
</table>
Winny answered 12/2, 2018 at 15:54 Comment(1)
The problem here is I cannot get the file from active storageThevenot

© 2022 - 2024 — McMap. All rights reserved.