-4

I am using Ruby 1.9.2 with Rails 3.2.1.

I would like to create a view to upload a CSV or tab delimited file, and displays the contents of the file on the same page using a table or pagination display, then process that data in JavaScript.

How can I do this? Please walk me through any code samples you have, I am a total noob in Ruby also.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
user836087
  • 2,271
  • 8
  • 23
  • 33

2 Answers2

0

First, write a view to upload your file. You can use Paperclip for this.

Assuming you have a resource Csv, your upload form could look like this:

<%= form_for @csv, :url => csv_path, :html => { :multipart => true } do |form| %>
  <%= form.file_field :attachment %>
<% end %>

Your model:

class Csv < ActiveRecord::Base
  attr_accessible :attachment
  has_attached_file :attachment
end

Your controller actions:

def create
  @csv = Csv.create( params[:csv] )
  # your save and redirect code here
end

def show
  @csv = Csv.find(params[:id])      
end

Having that, you can use something like this in your view:

CSV.foreach(@csv.attachment.path) do |row|
  # use the row here to generate html table rows
end

Note: this is just a general idea of how this can be done and you need to have the the resource added to your routes, Paperclip gem installed and configured, etc - read the doc on how to do all that.

Matt
  • 5,328
  • 2
  • 30
  • 43
  • Im a noob so i have some basic questions about making this thing work: What do you mean by a resource? is this a controller? What rails generate command should I use? – user836087 Dec 09 '12 at 04:56
  • I dont know why people are pointing to gems all over the place when someone is trying to learn rails. I dont want to use paperclip. How do I do I make this without the use of paperclip? – user836087 Dec 10 '12 at 02:32
  • Because gems make a lot of things easier and cleaner. If you want to learn Rails, just go and read [the guides](http://guides.rubyonrails.org/). Uploading files is described in the [form helpers](http://guides.rubyonrails.org/form_helpers.html#uploading-files) guide. There're also [many](http://stackoverflow.com/questions/3933061/how-to-upload-a-file-in-rails) [questions](http://stackoverflow.com/questions/9568753/how-to-upload-files-in-rails) already asked about it on SE. For general introduction there's also the [Rails tutorial](http://ruby.railstutorial.org/ruby-on-rails-tutorial-book). – Matt Dec 10 '12 at 13:07
-1

Just use a nice Ruby gem for parsing CSV files. This should point you in the right direction. http://fastercsv.rubyforge.org/

toolz
  • 63
  • 9
  • FasterCSV is built-into Ruby now as the [CSV module](http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html). – the Tin Man Dec 08 '12 at 21:04