Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Read csv file data with active storage

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
like image 826
Diego Llamas Velasco Avatar asked Feb 12 '18 15:02

Diego Llamas Velasco


People also ask

How does active storage work in rails?

Active Storage uses two tables in your application's database named active_storage_blobs and active_storage_attachments . After creating a new application (or upgrading your application to Rails 5.2), run rails active_storage:install to generate a migration that creates these tables.

Where does rails store CSV files?

In order to seed the database with the information from the CSV file, you will need to know the file path where your CSV file is located. To me it made the most sense to place by CSV file in the lib folder in my Rails API project directory.


1 Answers

Use download to obtain the file’s contents:

CSV.parse(materials_upload.csv_file.download, headers: true) do |row|
  # ...
end
like image 167
George Claghorn Avatar answered Sep 20 '22 15:09

George Claghorn