尝试将CSV数据导入活动记录时遇到问题。我的CSV是在google sheets中创建的,然后作为CSV下载。CSV中的某些条目在某些单词前后有引号“逻辑”)。下面是我为导入此数据而编写的脚本:
require 'csv'
homeDir = Dir.home
file = File.join(homeDir, "trdata-1.csv")
header = []
CSV.foreach(file, headers: true, :quote_char => '"', encoding: "UTF-8") do |row|
#possible cause
possible_cause = PossibleCause.find_by_description(row["Possible Cause"]) || PossibleCause.new.tap do |possible_cause|
# find the possible cause by its description, else make a new one.
possible_cause.description = row.to_s.slice(row["Possible Cause"])
#
puts possible_cause.description
end
#troubleshooting paths
troubleshooting_path = TroubleshootingPath.find_by_description(row["Troubelshooting Path"]) || TroubleshootingPath.new.tap do |troubleshooting_path|
# Find the troubleshooting path by its description, or else make a new one.
troubleshooting_path.description = row.to_s.slice(row["Troubleshooting Path"])
puts possible_cause.description
end
possible_cause.troubleshooting_paths << troubleshooting_path
#action steps
action_step = ActionStep.find_by_description(row["Action Step"]) || ActionStep.new.tap do |action_step|
action_step.description = row.to_s.slice(row["Action Step"])
puts possible_cause.description
end
troubleshooting_path.action_steps << action_step
possible_cause.save!
end我在rails控制台中执行脚本:
load 'lib/scripts/troubleshooting.rb'大多数数据加载都很好,并且按照我想要的方式正确地保存到数据库中。
下面是我尝试使用头文件导入的数据示例:
Frequency metric,Problem Symptom Title,Problem Symptom Desciption,Icon,Possible Cause,Troubleshooting Path,Action Step
2,Spindle issues,"When its time to run the job, the spindle doesn't run smoothly or doesn't work at all.",spindle_issue.png,Toggle switch on power supply is in the wrong position,Check toggle switch,"If using PWM, make sure it's set to ""Logic"""这一行将破坏脚本。“逻辑”一词用引号括起来。我试过去掉引号,它会运行得很好,所以肯定是引号导致了问题。我不知道为什么会发生这样的事情,而且在谷歌上搜索也没有找到多少结果。
发布于 2015-08-11 01:10:23
我相信,当您在相应的列中阅读时,您的问题不是转义引号,在本例中为"Action Step“。
最简单的选择是将CSV中的双引号更改为单引号,然后运行脚本。
发布于 2015-08-11 01:08:29
您可以从描述中gsub引号":
possible_cause.description.gsub('"', '')https://stackoverflow.com/questions/31925162
复制相似问题