Rails upload CSV file with header

2019-09-29 19:05发布

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.

2条回答
Lonely孤独者°
2楼-- · 2019-09-29 19:10

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.

查看更多
戒情不戒烟
3楼-- · 2019-09-29 19:24

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

查看更多
登录 后发表回答