2

我有这个来解析 CSV 文件:

csv_file = CSV.parse(
  file.read(),
  headers:              true,
  header_converters:    :symbol
)

它可以工作,但我想指定编码类型,所以我{encoding: 'UTF-8'}在 read 方法中添加:如下:

csv_file = CSV.parse(
  file.read({encoding: 'UTF-8'}),
  headers:              true,
  header_converters:    :symbol
)

但我得到这个错误:can't convert Hash into Integer

我只是看不出有什么问题。我已经检查了文档,但它说你可以像这样传递编码,但它确实需要文件作为第一个参数,所以它可能会停在那里,但肯定因为它已经知道正在读取什么文件,所以应该没问题。

我该如何解决这个问题?

更新:

我已更新为以下内容:

def import
  if params[:import_coasters]
    file = params[:import_coasters][:file]
    Park.import_from_csv(file)


def self.import_from_csv(file)
  Park.destroy_all

  csv_file = CSV.parse(
    File.read(file, {encoding: 'UTF-8'}),
    headers:              true,
    header_converters:    :symbol
  )

但我收到以下错误:

无法将 ActionDispatch::Http::UploadedFile 转换为字符串

4

2 回答 2

4

你很近。尝试这个:

# Step 1: convert the uploaded file object to a file name
uploaded_file = params[:import_coasters][:file]
file_name = uploaded_file.path

# Step 2: To get the input text and see if it's what you expect
text = File.read(
  file_name, 
  {encoding: 'UTF-8'}
)

# Parse the text
csv_file = CSV.parse(
  text,
  headers: true,
  header_converters: :symbol
)

来自 IO.read 上的 Ruby 1.9.3 文档:

“如果最后一个参数是一个散列,它指定内部 open() 的选项。键如下。open_args: 是其他人独有的。”

http://www.ruby-doc.org/core-1.9.3/IO.html#method-c-read

另外,请查看文档,UploadedFile因为它实际上不是典型的 Ruby File 对象:

http://api.rubyonrails.org/classes/ActionDispatch/Http/UploadedFile.html

于 2012-11-25T06:24:48.020 回答
1

这是因为 File.read() 期望文件名作为第一个参数。您正在传递 ActionDispatch::Http::UploadedFile 。如果您查看文档,您会看到 UploadedFile 已经有一个 read 方法,因此您可以尝试:

   csv_file = CSV.parse(
    file.read({encoding: 'UTF-8'}),
    headers:              true,
    header_converters:    :symbol
  )
于 2012-11-25T23:38:16.093 回答