0

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

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 时出现此错误

耙中止!Encoding::UndefinedConversionError: "\xC2" from ASCII-8BIT to UTF-8: INSERT INTO "sections" ("building", "category", "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:intype_cast'

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

4

1 回答 1

1

使用此默认值显示您的线路将不胜感激。

如果要捕获错误,请使用一些 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
于 2013-03-28T13:47:56.933 回答