我有一个上传的 CSV 文件,我是这样解析的:
CSV.foreach(@my_file.file.path) do |row|
puts row[1]
end
传入的CSV文件至少有以下列:“id”、“name”、“number”、“phone”、“food”。
我想做这样的事情:
CSV.foreach(@my_file.file.path) do |row|
//find the columns in "row" associated with "id", "name", "number"
//even though I don't know definitively which column they will be in
//for example, "name" may be the 2nd or 3rd or 4th column (etc)
//insert into my_table values(id, name, number)
end
请注意,CSV 文件的第一行始终是列名,但是在不同的文件中,这些列的顺序可能会有所不同。
最佳答案
下面是一段代码,它只会将您关心的字段收集到一个哈希数组中:
require 'csv'
fields_to_insert = %w{ id name food number phone }
rows_to_insert = []
CSV.foreach("stuff.csv", headers: true) do |row|
row_to_insert = row.to_hash.select { |k, v| fields_to_insert.include?(k) }
rows_to_insert << row_to_insert
end
给定 stuff.csv
的以下内容:
junk1,name,junk2,food,id,junk4,number,phone
foo,Jim,bar,pizza,123,baz,9,555-1212
baz,Fred,bar,sushi,55,foo,44,555-1213
rows_to_insert
将包含:
[{"name"=>"Jim",
"food"=>"pizza",
"id"=>"123",
"number"=>"9",
"phone"=>"555-1212"},
{"name"=>"Fred",
"food"=>"sushi",
"id"=>"55",
"number"=>"44",
"phone"=>"555-1213"}]
我会接受并使用 activerecord-import一次插入它们:
SomeModel.import(rows_to_insert)
您可以在 CSV 循环中一次插入一条记录,但效率很低,而且因为 id
通常是 protected 属性,您不能批量分配它,所以您会必须这样做才能插入一条记录:
some_model = SomeModel.new(row_to_insert.select { |k, v| k != "id" }
some_model.id = row_to_insert["id"]
some_model.save!
...或类似的东西。
关于ruby-on-rails - Ruby - 将 CSV 中的条目插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15752079/