【发布时间】:2015-05-31 02:29:29
【问题描述】:
在 ruby/rails 中导入此 CSV 文件时遇到问题
我得到的错误信息是这样的:
Missing or stray quote in line 1 (CSV::MalformedCSVError)
但我不确定发生了什么,因为我的 CSV 看起来非常好。以下是示例数据:
"lesley_grades","lesley_id","last","first","active","site","cohort","section","sections_title","faculty","completed_term_cred","term","sec_start_date","sec_end_date","grade","stc_cred","active_program","most_recent_program","intent_filed","stc_term_gpa","sta_cum_gpa","start_term","prog_status","last_change_date"
,1234456,John,Doe,TRUE,"Baltimore, MD",0002012,14/FA_ERLIT_6999_U15AA,Directed Independent Study,"Jane Hicks , Jill Saunders",2,14/FA,9/3/14,12/17/14,B-,2,EME.2270.TCBAL.01,EME.2270.TCBAL.01, ,3.3,3.148,12/SU,A,9/2/14
,1234455,John,Doe,TRUE,"Baltimore, MD",0002012,14/FA_ERSPD_6999_U15AG,Directed Independent Study,"Jane Hicks , Jill Saunders",3,14/FA,9/3/14,12/17/14,A-,3,EME.2270.TCBAL.01,EME.2270.TCBAL.01, ,3.3,3.148,12/SU,A,9/2/14
为了给出上下文,实际上 csv 看起来像这样,其中 lesley_grades 作为第一列。 over CSV 脚本文件将查找第一列并检查 Active Record 对象是否处于活动状态,然后将其存储在具有完全相同模型名称的数据库中,假设所有迁移都是预设的。
lesley_grades lesley_id last first active
1234556 Doe John TRUE
1123445 Doe John TRUE
这是导致我出现问题的部分代码
def import!(csv)
csv_reader = CSV.parse(csv)
ActiveRecord::Base.transaction do
csv_reader.each do |row|
set_record_class_and_columns(row) if header_row?(row)
if columns_mapping_defined? && record_class_defined? && record_row?(row)
import_row(row)
end
end
if imports_failed?
puts 'Aborting importing and rolling back...'
show_errors
raise ActiveRecord::Rollback
end
end
结束
无法通过这一行csv_reader = CSV.parse(csv)
在我把引号放在标题中之前,我收到了这个错误
Unquoted fields do not allow \r or \n (line 1). (CSV::MalformedCSVError)
更新
CSV 从命令行启动,如下所示:
rails runner scripts/import_csv.rb < lesley_grades.csv
然后在这里被初始化
CSVImporter.new.import!($stdin)
但正如@smathy 建议的那样,我将方法更改为 CSV.parse(csv.gsub /\r/, '')
但现在采用gsub 块的def import! 方法会产生此错误
in `import!': undefined method `gsub' for #<IO:<STDIN>> (NoMethodError)
不确定如何使 CSV 成为对象?
有任何建议或重构来完成这项工作吗? 谢谢大家
【问题讨论】:
标签: ruby-on-rails ruby csv