Mark Locklear
Mark Locklear

Reputation: 5335

Rails Seed.rb ncoding::UndefinedConversionError: "\xC2" error when importing CSV

My seed file looks like this...

csv_file_path = 'db/coned.csv'
count = 0
CSV.foreach(csv_file_path) do |row|
  row = Section.new({
    :supervisor => row[0],
    :catagory => row[1],
    :title => row[2],
    :description=> row[3],
    :days => row[4],
    :start_date => row[5],
    :end_date => row[6],
    :start_time => row[7],
    :end_time => row[8],
    :course_id => row[9],
    :room => row[10],
    :building => row[11],
    :location => row[12],
    :tuition => row[13],
    :lab_fee => row[14],
    :insurance_fee => row[15],
    :technology_fee => row[16]
  })
  row.save!
  puts "Added row #{count}"
  count+=1
end

...and I am getting this error when I run rake db:seed

rake aborted! Encoding::UndefinedConversionError: "\xC2" from ASCII-8BIT to UTF-8: INSERT INTO "sections" ("building", "catagory", "course_id", "created_at", "days", "description", "end_date", "end_time", "insurance_fee", "lab_fee", "location", "room", "start_date", "start_time", "supervisor", "technology_fee", "title", "tuition", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) /home/johnmlocklear/.rvm/gems/ruby-1.9.2-p320/gems/activerecord-3.2.11/lib/active_record/connection_adapters/sqlite_adapter.rb:208:in encode' /home/johnmlocklear/.rvm/gems/ruby-1.9.2-p320/gems/activerecord-3.2.11/lib/active_record/connection_adapters/sqlite_adapter.rb:208:intype_cast'

Any ideas on how I can just catch this error and throw out that row and continue on importing rows. Or possibly some kind of forced encoding?

Upvotes: 0

Views: 320

Answers (1)

pierallard
pierallard

Reputation: 3371

Showing your line with this default will be appreciated.

If you want to catch the error, use some Exception :

CSV.foreach(csv_file_path) do |row|
  begin
    row = Section.new({
      :supervisor => row[0],
      ....
      :technology_fee => row[16]
    })
    row.save!
    puts "Added row #{count}"
    count+=1
  rescue Exception
    Rails.logger.error "Encountred error at line #{row.inspect}"
  end
end

Upvotes: 1

Related Questions