Ruby CSV |如何在阅读CSV时跳过几列?

时间:2016-12-22 16:54:40

标签: ruby-on-rails ruby activerecord activerecord-import

我使用Active record Import gem将数据从CSV文件批量导入数据库。但我想在导入时跳过几个CSV列。

例如,我的xaa.csv包含name,author,author_id,rating等标题。 导入时,我想跳过' author_id'列值并导入所有其他列。

books = CSV.read("/public/xaa.csv") //What more should I do here to skip the 3rd column
columns = [:name, :author, :rating]
Book.import columns, books, :validate => false

2 个答案:

答案 0 :(得分:4)

books = []

CSV.foreach('/public/xaa.csv', headers: true) do |row|
  books << [row['name'], row['author'], row['rating']]
end

columns = [:name, :author, :rating]
Book.import(columns, books, validate: false)

答案 1 :(得分:0)

books = CSV.readlines(path, headers:true).map{|row| row.values_at('name','rating') }

vegetaras的版本内存效率稍高。