Hello Doug,
2006/2/27, Doug Bromley <doug.bromley@gmail.com>:> I was hoping you could help me. I need the ability to upload a large
> quantity of data via CSV - via an upload form. The CSV file then needs
> parsing and the data entering into the relevant module.
Make a form with an upload field. Something like this:
# app/views/upload/index.rhtml
<%= start_form_tag({:action => :parse}, {:multipart => true}) %>
<p class="error"><%= flash[:error] %></p>
<label>Upload CSV file: <%= file_field_tag ''data''
%></label>
<%= submit_tag ''Upload and parse'' %>
<%= end_form_tag %>
In your controller, do this:
# app/controllers/upload_controller.rb
require ''csv''
class UploadController < ApplicationController
def parse
if params[:data].size.zero? then
flash[:error].now = ''Forgot to upload some data''
render ''index''
return
end
params[:data].rewind # Make sure Tempfile / StringIO is at start of data
row_count = 0
CSV::Reader.parse(params[:data]) do |row|
row_count += 1
# Do something interesting with row:
# row[0] is first column, row[1] is second column, etc.
end
flash[:status] = "Imported #{row_count} rows"
end
end
# app/views/upload/parse.rhtml
<p><%= flash[:status] %></p>
<p><%= link_to ''See imported data'', :controller =>
''there'', :action =>
''see-it'' %></p>
WARNING: Not a single line of code was tested in this E-Mail.
Hope that helps !
--
Fran?ois Beausoleil
http://blog.teksol.info/