Importing a CSV File from a Form

written by damien on December 7th, 2007 @ 02:04 AM

This article is a translation of the articles I wrote on my other blog during July 2007.

During my placement at Dexem I was mainly developing Voice Publisher: a tool used to create Interactive Voice Responses generated using the VoiceXML language. For this software (developed using Ruby on Rails), I have to import a CSV file into the database. As it is not very well documented, here is what I did to make it work.

To recover a file from a form you just need two things: declaring correctly the form, and a field which will permit you to recover the file:

<%= start_form_tag({:action => 'import_csv', :id => my_object}, :multipart => true) %>
  <label for="csv_file">File to Upload</label>
  <%= file_field_tag "csv_file" %>
<%= end_form_tag %>

Then in the action used to import the file:

def import_csv
  begin
    CSV::Reader.parse(params[:csv_file]).each do |row|
      unless row[0].nil? or row[1].nil?
        MyObject.create(:name => row[0], :value => row[1])
      end
    end
  rescue
    flash[:error] = "There was an error parsing your CSV file"
  end
end

In order to check the file is specified when the form is submitted, you may want to add the following code to your action:

unless params[:csv][:file] == "" || params[:csv][:file].nil?
  csv_file = params[:csv][:file].read
  unless csv_file == ""
    # read the CSV file from here
    # but this time use csv_file instead of params[:csv][:file]
  end
end

The first test...

unless params[:csv][:file] == "" || params[:csv][:file].nil?

...will check a file is specified for Firefox and Internet Explorer. The second test...

unless csv_file == ""

...is for Opera. If no file is given, Opera will still give us a StringIO object, which when read will give an empty string. On the contrary, Firefox and Internet Explorer will not give a StringIO if no file is specified, instead they will give an empty string.

That's it ! Now you know how to read a csv file from a form using Ruby on Rails. You may want to have a look at the fastercsv library which will provide, as the name says, faster reading of your csv files :)

Comments are closed

Options:

Size

Colors