我将创建一个导轨应用程序来导入csv文件并在网页中显示其内容。除了一件事,一切都很好。如果csv文件包含带引号的字符串,例如“”,“,”,那么该程序无效。
我的app / models / user.rb文件是: -
class User < ActiveRecord::Base
require 'csv'
def self.import(file)
CSV.foreach(file.path, headers:true) do |row|
User.create! row.to_hash
end
end
end
答案 0 :(得分:1)
您可以为此错误使用代码创建救援 - 如下所示 - 可能对你有用!
def self.import(file)
quote_chars = %w(" | ~ ^ & *)
begin
CSV.foreach(file, headers: :first_row, quote_char: quote_chars.shift) do |row|
User.create! row.to_hash
end
rescue CSV::MalformedCSVError
quote_chars.empty? ? raise : retry
end
end