Rails Read csv file data with active storage

自闭症网瘾萝莉.ら 提交于 2019-12-05 02:37:51

Use download to obtain the file’s contents:

CSV.parse(materials_upload.csv_file.download, headers: true) do |row|
  # ...
end

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

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!