Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smarter CSV and Uploaded CSV File

For my application I am uploading a file via file_field_tag. How do I use that file with SmarterCSV? I have tried something like this SmarterCSV.process(@file.tempfile.path) and it just returns an empty array even though there is data in the CSV.

Any thoughts?

like image 830
Jackson Avatar asked Feb 14 '23 23:02

Jackson


2 Answers

The proposed answer does not work.

If you however do it like this:

    clients_data = params[:file_categories]
    clients = SmarterCSV.process(clients_data.tempfile, {:chunk_size => 1, :key_mapping => {:ca_id => :id, :ca_desc => :name}})

This works fine. You need to use tempfile instead of original_filename.

like image 79
rept Avatar answered Feb 19 '23 12:02

rept


It's not clear what @file is, but if from a typical form and assigned something like:

@file = params[:resource][:file_tag_name]

then try:

SmarterCSV.process(@file.original_filename)

or with CSV:

CSV.parse(@file.original_filename)

The object that Rails creates in the params hash for a file upload is an instance of a subclass of the IO class, so you need to get to the underlying file to pass it to SmarterCSV.

For more information about how Rails handles file uploading, please see http://guides.rubyonrails.org/form_helpers.html#what-gets-uploaded

like image 42
Troy Avatar answered Feb 19 '23 12:02

Troy