Search code examples
ruby-on-railsrubyactiverecordactiverecord-import

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


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

Solution

  • 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)