带空格的CSV记录未保存到数据库

时间:2014-06-10 18:43:18

标签: csv ruby-on-rails-4

我正在尝试将以下类型的CSV记录保存到数据库中:

9,Lambert,Kent D,Senator

但它没有保存在DB中,事务正在回滚并发出此错误。

{"state_senate_district_id"=>"9", "last_name"=>"Lambert", "first_name"=>"Kent D", "tag"=>"Senator"}
   (0.2ms)  BEGIN
   (0.1ms)  ROLLBACK
["First name should contain only alphabets"]

因此first_name = "Kent D"中有一个空格,因此它不允许空格,因此它不会保存到数据库。

以下是解析CSV的代码:

hash = {}
CSV.foreach('Senator.csv', {:headers=>:first_row}) do |line|
hash['state_senate_district_id'] = line[0]
hash['last_name'] = line[1]
hash['first_name'] = line[2]
hash['tag'] = line[3]
puts hash
senator = Senator.new(hash)
unless senator.save(hash)
    err = senator.errors.full_messages
    p err
    File.open("errors", "a") do |csv|
      err.each do |c|
        csv << "\n"
        csv << "||||||"
        csv << [c]
      end
    end
  end

1 个答案:

答案 0 :(得分:0)

您可能在Senator模型中有一个阻止first_name字段占用空间的验证规则。删除该验证或更改它以允许空格。