【发布时间】:2015-02-03 19:01:06
【问题描述】:
我在 Rails 应用程序中使用 ruby 的 CSV 类(ruby 2.1.5)从上传的 csv 文件加载记录。用户正在使用“另存为”从 Excel 创建 csv 文件,并且根据数字的格式,它们可能会保存为带逗号的带引号的字符串——在这种情况下,逗号后面的数字部分将被删除。
如果输入值为"3,500",则应保存3500,但改为3。
我意识到可以在 Excel 中清理它,但它似乎也应该很容易处理(如果我必须告诉他们程序无法处理这个问题,我会从用户那里得到一个主要的 WTF基本情况。)此外,由于 csv 文件的标题与数据库中的列名匹配,我不必编写特定于列的处理程序 - 我只需进行属性分配。我希望保持这种状态,因为我的受影响列比我在示例中包含的要多得多。
输入记录:
recordid,valcurrent,valdate
11015,"3,500",6/7/2013
处理函数
def import_csv(file)
CSV.foreach(file.path, headers: true, header_converters: :symbol, skip_blanks: true, converters: :all) do |row|
# hash the input row
row_hash = row.to_hash
# create a new row with the hash in original_record
fl = self.forecast_lines.create(original_record: row_hash.to_s)
# write the hash to the record attributes
fl.attributes = row_hash
fl.save
end
end
原始记录哈希:
Original record: {:recordid=>"11015", :valcurrent=>"3,500", :valdate=>"6/7/2013"}
valcurrent 的数据类型是浮点数。但是保存到数据库中的有效值不是3500.0,而是3.0。
【问题讨论】:
标签: ruby-on-rails ruby csv