我想将数据从CSV文件导入到现有的数据库表中。我不想保存CSV文件,只是从它的数据,并把它放入现有的表。我使用Ruby 1.9.2和Rails 3。

这是我的桌子:

create_table "mouldings", :force => true do |t|
  t.string   "suppliers_code"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "name"
  t.integer  "supplier_id"
  t.decimal  "length",         :precision => 3, :scale => 2
  t.decimal  "cost",           :precision => 4, :scale => 2
  t.integer  "width"
  t.integer  "depth"
end

你能给我一些代码,告诉我最好的方法,谢谢。


当前回答

如果您想使用SmartCSV

all_data = SmarterCSV.process(
             params[:file].tempfile, 
             { 
               :col_sep => "\t", 
               :row_sep => "\n" 
             }
           )

这表示每个行“\t”中以制表符分隔的数据,行由新行“\n”分隔

其他回答

我知道这是一个老问题,但它仍然在谷歌的前10个链接。

逐个保存行不是很有效,因为它会导致循环中的数据库调用,您最好避免这种情况,特别是当您需要插入大量数据时。

使用批处理插入更好(而且更快)。

INSERT INTO `mouldings` (suppliers_code, name, cost)
VALUES
    ('s1', 'supplier1', 1.111), 
    ('s2', 'supplier2', '2.222')

您可以手动构建这样的查询,而不是使用Model.connection。执行(原始SQL字符串)(不推荐) 或者使用gem activerecord-import(它于2010年8月11日首次发布)在这种情况下,只需将数据放在数组行中并调用Model。进口的行

详情请参阅gem文档

require 'csv'    

csv_text = File.read('...')
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
  Moulding.create!(row.to_hash)
end

你可以试试Upsert:

require 'upsert' # add this to your Gemfile
require 'csv'    

u = Upsert.new Moulding.connection, Moulding.table_name
CSV.foreach(file, headers: true) do |row|
  selector = { name: row['name'] } # this treats "name" as the primary key and prevents the creation of duplicates by name
  setter = row.to_hash
  u.row selector, setter
end

如果这是您想要的,您还可以考虑从表中删除自动递增的主键,并将主键设置为name。或者,如果有一些组成主键的属性组合,则将其用作选择器。不需要索引,这样会更快。

这是有帮助的。它也有代码示例:

http://csv-mapper.rubyforge.org/

或者对rake任务做同样的事情:

http://erikonrails.snowedin.net/?p=212

如果您想使用SmartCSV

all_data = SmarterCSV.process(
             params[:file].tempfile, 
             { 
               :col_sep => "\t", 
               :row_sep => "\n" 
             }
           )

这表示每个行“\t”中以制表符分隔的数据,行由新行“\n”分隔