Forum: Ruby on Rails Upload & Parse CSV

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Doug B. (Guest)
on 2006-02-27 18:05
(Received via mailing list)
Hi All

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.

Does anyone have experience of this or perhaps knows of a posting,
generator, existing code or any help at all?  I've been looking but not
come
across anything so far.  I can do this in PHP but would very much like
to
crack this in Rails.

Many thanks for any help.

All the best.

Doug
Francois B. (Guest)
on 2006-02-27 18:14
(Received via mailing list)
Hello Doug,

2006/2/27, Doug B. <removed_email_address@domain.invalid>:
> 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 !
Barb W. (Guest)
on 2007-12-28 03:23
Hello,

 I am trying to get this to work in Rails 2.02.  Could anyone tell me
how to modify the post by Francois B. ?

Thanks!
Barb
This topic is locked and can not be replied to.