Rails upload CSV file with header

我与影子孤独终老i 提交于 2019-12-25 19:58:24

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/13781438/rails-upload-csv-file-with-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!