Rails上传带有标题的CSV文件 [英] Rails upload CSV file with header
问题描述
我使用Ruby 1.9.2与Rails 3.2.1。
我想创建一个视图来上传CSV或制表符分隔文件,并显示使用表格或分页显示在同一页面上的文件内容,然后在JavaScript中处理该数据。
我该如何做?
首先,写一个视图到上传您的文件。您可以使用回形针进行此操作。
假设您有一个资源 Csv
,您的上传表单可能如下所示:
<%= form_for @csv,:url => csv_path,:html => {:multipart => true} do | form | %>
<%= form.file_field:attachment%>
<%end%>
您的型号:
class Csv < ActiveRecord :: Base
attr_accessible:attachment
has_attached_file:attachment
end
您的控制器操作:
def create
@csv = Csv.create(params [:csv])
#你的保存和重定向代码在这里
end
def show
@csv = Csv.find(params [:id])
end
这样,你可以在你的视图中使用这样的东西:
CSV.foreach(@ csv.attachment.path)do | row |
#使用此处的行生成html表行
end
注意:这只是一个一般的想法,如何这可以做,你需要将资源添加到您的路线,Paperclip gem安装和配置等等 - 阅读文档如何做所有这一切。
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.
解决方案 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.
这篇关于Rails上传带有标题的CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!