我正在使用 ruby 将 csv 文件从前端导入到 mysql 中。 这是我的 Controller 代码
require 'csv' def csv_import @parsed_file=CSV::Reader.parse(params[:dump][:file]) n=0 @parsed_file.each do |row| c=CustomerInformation.new c.job_title=row[1] c.first_name=row[2] c.last_name=row[3] if c.save n=n+1 GC.start if n%50==0 end flash.now[:message]="CSV Import Successful, #{n} new records added to data base" end
This is my front end code.
<pre>
<% form_for :dump, :url=>{:controller=>"customer_informations", :action=>"csv_import"}, :html => { :multipart => true } do |f| -%>
<table">
<tr>
<td>
<label for="dump_file">
Select a CSV File :
</label>
</td>
<td >
<%= f.file_field :file -%>
</td>
</tr>
<tr>
<td colspan='2'>
<%= submit_tag 'Submit' -%>
</td>
</tr>
</table>
<% end -%>
</pre>
现在我想要的是,我在数据库中有大约 30 列,csv 将包含 30 个列标题。另外,为了进行检查,我将使用 textfield 要求其中一列作为输入,这样 csv 表中就有 29 列。根据用户选择的选项,剂量 29 列将附加到文本框中所选的实体。
如有任何帮助,我们将不胜感激。
谢谢
最佳答案
如果您使标题与表格列相同,则您的代码应该简单如下:
CSV::foreach(filename, :headers => true) do |row|
Model.new(row.to_hash).save
end
关于使用Ruby导入Mysql数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18098943/