Luigi
Luigi

Reputation: 5603

Rails 4.0 store temporary CSV file

I am attempting to load a CSV file through a submit_tag form. I need the CSV contents to be stored in memory so that I can use them to send emails to all of the contacts loaded in from the CSV. I then need to scrap the CSV file and forget about it.

Does anyone have a reference or tips on how to store a csv file into memory, perform some actions on it, and then forget about it?

Upvotes: 2

Views: 1246

Answers (1)

struthersneil
struthersneil

Reputation: 2750

In your controller action that receives the submit action from your form, your CSV file will be available as a File IO object in your params hash. So you can just load a CSV object from there, e.g.

require 'csv' # Ruby standard library 

...

def create
  ...
  csv = CSV.load params[:csv_file]
  # use your in-memory csv object and forget about it afterwards
  ...
end

Check out http://ruby-doc.org/stdlib-2.0.0/libdoc/csv/rdoc/CSV.html for more reference.

You can also pass an IO object to CSV.open like this:

CSV.open(params[:csv_file]) do |csv|
  # do something with your csv data
end

Upvotes: 2

Related Questions