因此,我正在尝试导入具有以下格式的 RoR 的 CSV 文件:
header,data,header,data,header,data
一个例子是:
name,peter,age,12,birthplace,london
name,john,age,30,birthplace,new york
导入文件后,如何分配与数据库匹配的 header 。顺序可能每次都不同,一些字段可能在 CSV 中,而其他字段可能不在。我将如何在我的模型中处理这个问题?
最佳答案
您可以按照以下方式进行操作:
all_attributes = []
CSV.foreach('path/to/file') do |row|
attributes = {}
row.each_with_index do |column, i|
next if i % 2 != 0 # skip every other column
attributes[column.to_sym] = row[i+1]
end
all_attributes << attributes
end
此代码依赖于 header 始终位于值之前的 1 列这一事实。
关于ruby-on-rails - 数据旁边的 CSV header - Rails Import,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27848388/