Parsing CSV files sent via form post in Ruby on Rails
I’m not sure why it took me a while to figure this out but it did. The Ruby CSV documentation is really weak and really only explains how to read from a file. I googled around and couldn’t find anyone else talking about how to parse a CSV file sent via a form post (StringIO). I didn’t want to save it to a temp file just so I could follow the CSV docs examples. Here’s what I eventually got to work. Its so short and simple I feel silly for not figuring it out sooner.
parsed_file = CSV::Reader.parse(params[:dump][:file])
parsed_file.each do |row|
p row[0]
end

July 20th, 2007 at 3:47 pm
What does your form look like?
I am having the same problem as you. I have a form to upload a *.csv file, I want to parse that file and input it into my DB. I saw your bits of code, and I am wondering what your form looks like, and how it operates for you to just call parse() on your params like that. My params consist of the path name of the file, or just the filename itself (in firefox), and I do not believe that is correct. Is there anyway you could “spill it out” so to speak ?
July 20th, 2007 at 4:02 pm
What does your form look like? I do not understand how this works, can you please explain this a little bit further?
July 20th, 2007 at 4:05 pm
Could you please explain this in more depth. What does your form look like? I am very intrested!
sincerely,
Nick
July 26th, 2007 at 12:15 am
It appears that the form is something like this:
:import do %>
Another variant is
:import do %>
Paste your CSV file here:
August 3rd, 2007 at 4:01 pm
[source:ruby]
< %= start_form_tag ({:action=> “import”}, :multipart => true)%>
File to import: < %= file_field 'dump', 'file' %>
< %= submit_tag "Import" %>
< %= end_form_tag %>
[/source]
Sorry for the delay.