1

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
  • 1
    What have you tried? Have you looked at the headers option. Read the headers and then you can selectively import each row based on the column. I do that all the time Commented Dec 22, 2016 at 17:02
  • try this columns = [:name, :author, nil, :rating] Commented Dec 22, 2016 at 17:28

2 Answers 2

7
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)
Sign up to request clarification or add additional context in comments.

2 Comments

This is functionally no different than the original code. For the "how to skip 3rd column" requirement, you need to set row['rating'] = nil, or replace nil in the 3rd position in the books << line
Thankyou @vegetaras.
2
books = CSV.readlines(path, headers:true).map{|row| row.values_at('name','rating') }

vegetaras's version is slightly more memory efficient.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.