Monday 2 July 2012

Importing a CSV File from Upload in Rails >= 3

For some reason I found the documentation for CSV's really bad!

What I wanted to do is accept a file from a form and parse it into a list of users to be added to the database without saving the CSV file. (Note: I DO save the file via the Paperclip Gem for logging purposes but I do all the processing from the file before it is saved to the database.)

When you have uploaded the file using Form_Tag, the file is usually in params[:name] where :name is tag you gave to file_field_tag :name
If you are using a Form_For, which by the way is strange if you do not intend to save it to the model in question, the file will be in params[:model][:name] from  f.file_field :name
The magic part is to actually get to the file you need to call .read on it.

In the View remember to make it multipart to accept files.


<%= form_for @model, :html => { :multipart => true } do |f| %>
  <%= f.label :file %><br />
  <%= f.file_field :file %><br /> 
  <%= f.submit "Upload" %>
<% end %>



In the Controller require csv, you do not need to install it as a gem but you do need to require it as it is in standard library not core.

require 'csv'
def my_method
@lines = []
CSV.parse(params[:submission][:file].read) do |row|
      @lines << row
end


Replace the yellow bits with whatever you want to do with your CSV file.
Have fun!

No comments:

Post a Comment