【问题标题】:Rails Import/Parse from CSV UTF-8 Missing ColumnRails 从 CSV UTF-8 缺失列导入/解析
【发布时间】:2019-10-31 18:37:58
【问题描述】:

所以我正在努力让用户从 CSV 文件中导入数据。现在所有字段都将正确导入,除了第一个字段。

我发现文件类型正在影响导入。

我的代码如下:

class Import < Operation
require 'csv'
def call(file, training_event_id)
  csv_data = CSV.parse(file.read, headers: true)
  list_occo = []
  csv_data.each do |row|
    occupant = Occupant.new
    occupant.account_number = row['Account Number']
    occupant.check_in = row['Check In']
    binding.pry
    occupant.training_event_id = training_event_id
    list_occo << occupant
  end
  binding.pry
  occo_errors = check_file(list_occo)
  list_occo.each(&:save) if occo_errors.empty?
  return occo_errors
end

当我执行 binding.pry 并检查占用者时,我在执行 CSV UTF-8 时的帐号为零。如果我切换到直接 CSV 不是问题。有没有办法将 CSV UTF-8 转换/切换为 CSV?我想/尝试在解析上使用某种编码,例如: encoding: 'iso-8859-1' 但这不起作用。

有没有办法转换 CSV UTF-8,或者有没有办法直接检查文件格式以确保它是 CSV 而不是 CSV UTF-8?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    以防万一将来有人遇到此问题。我使用 CSV.read(file.path) 查看了 rails 控制台中的文件,并注意到 U+FEFF 在第一列标题之前。有一个关于 BOM 和 UTF-8 问题的信息的兔子洞。不想做 CSV/File.open 我尝试了一些事情,比如在 utf-8 上进行拆分、gsub、文件检查等。然后我只是将 csv_data 行更改为:

    csv_data = CSV.parse(File.read(file, encoding: 'bom|utf-8'), headers: true)
    

    然后在我的控制器中,我将它从 (params[:file]) 更新为 (params[:file].path),因为我收到了一个错误

    没有将 ActionDispatch::Http::UploadedFile 隐式转换为 字符串

    希望这对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 2013-06-13
      • 2012-01-12
      • 1970-01-01
      • 2016-01-08
      • 2016-10-09
      • 2012-11-07
      • 2019-11-09
      • 1970-01-01
      • 2014-06-30
      相关资源
      最近更新 更多