【问题标题】:CSV record with spaces is not saving to the database带空格的 CSV 记录未保存到数据库
【发布时间】: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


【解决方案1】:

您可能在Senator 模型中有一个验证规则,它阻止first_name 字段包含空格。删除该验证或将其更改为允许空格。

【讨论】:

  • 非常感谢,模型中有验证:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多