【发布时间】:2014-06-10 18:43:17
【问题描述】:
我正在尝试将以下类型的 CSV 记录保存到数据库中:
9,Lambert,Kent D,Senator
但它没有保存在数据库中,事务正在回滚并出现此错误。
{"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
【问题讨论】:
-
试试 {:col_sep => ","}
-
请包括您的
Senator模型,因为这很可能是问题所在。 -
非常感谢,模型中有验证:)
标签: csv ruby-on-rails-4