上传CSV文件时出现迷走或流浪的报价(CSV :: MalformedCSVError)

时间:2017-09-22 23:10:13

标签: ruby-on-rails csv import controller

我正在尝试上传以下CSV文件:

1,Order,"{\"customer_name\":\"Jack\",\"customer_address\":\"Trade St.\",\"status\":\"unpaid\"}"
2,Order,"{\"customer_name\":\"Sam\",\"customer_address\":\"Gecko St.\",\"status\":\"unpaid\"}"
1,Product,"{\"name\":\"Laptop\",\"price\":2100,\"stock_levels\":29}"
1,Order,"{\"status\":\"paid\",\"ship_date\":\"2017-01-18\",\"shipping_provider\":\"DHL\"}"
2,Product,"{\"name\":\"Microphones\",\"price\":160,\"stock_levels\":1500}"
1,Invoice,"{\"order_id\":7,\"product_ids\":[1,5,3],\"status\":\"unpaid\",\"total\":2500}"
1,Invoice,"{\"status\":\"paid\"}"

当我尝试上传时,出现以下错误: CustomersController#import

中的CSV :: MalformedCSVError

这里特别突出了第三行:

class Customer < ApplicationRecord
  def self.import(file)
    CSV.foreach(file.path, headers: true) do |row|
      Customer.create! row.to_hash
    end
  end

这是我在控制器中进行的导入:

  def import
    Customer.import(params[:file])
    redirect_to customer_path, notice: "Customer Added Successfully"
  end

我知道这个问题可能来自引用语法错误,但我没有看到我在第一行的引号有任何问题。一切似乎都井井有条,我相信其他一切都是正确的,所以我有点难过。谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

我将\"替换为'并且有效:

1,Order,"{'customer_name':'Jack','customer_address':'Trade St.','status':'unpaid'}"

我同意这有点奇怪。希望解决方案对你有用。