Ruby CSV | How to skip few columns while reading CSV?

2.4k views Asked by At

I am bulk importing data from a CSV file into database using Active record Import gem. But I want to skip few CSV columns when importing.

For example, my xaa.csv has headers like name, author, author_id, rating. While importing, I want to skip the 'author_id' column values and import all the other columns.

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

There are 2 answers

2
vegetaras On BEST ANSWER
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)
0
andynu On
books = CSV.readlines(path, headers:true).map{|row| row.values_at('name','rating') }

vegetaras's version is slightly more memory efficient.