Rails Seed.rb ncoding :: UndefinedConversionError:导入CSV时出现“\ xC2”错误

时间:2013-03-28 13:21:05

标签: ruby-on-rails csv seed

我的种子文件看起来像这样......

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

...当我运行rake db:seed

时,我收到此错误 耙子流产了! 编码:: UndefinedConversionError:从ASCII-8BIT到UTF-8的“\ xC2”: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“)价值观(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) /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:in type_cast'

关于如何捕获此错误并丢弃该行并继续导入行的任何想法。或者可能是某种强制编码?

1 个答案:

答案 0 :(得分:1)

显示您的默认行。

如果要捕获错误,请使用一些异常:

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