Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 数据旁边的CSV标题-Rails导入_Ruby On Rails_Ruby_Csv_Import - Fatal编程技术网

Ruby on rails 数据旁边的CSV标题-Rails导入

Ruby on rails 数据旁边的CSV标题-Rails导入,ruby-on-rails,ruby,csv,import,Ruby On Rails,Ruby,Csv,Import,因此,我尝试导入一个具有RoR的CSV文件,其格式如下: header,data,header,data,header,data 例如: name,peter,age,12,birthplace,london name,john,age,30,birthplace,new york 导入文件后,如何分配与数据库匹配的标头。每次的顺序可能不同,一些字段可能在CSV中,而其他字段可能不在CSV中。我将如何在我的模型中处理此问题?您可以按照以下操作: all_attributes = [] CSV

因此,我尝试导入一个具有RoR的CSV文件,其格式如下:

header,data,header,data,header,data
例如:

name,peter,age,12,birthplace,london
name,john,age,30,birthplace,new york

导入文件后,如何分配与数据库匹配的标头。每次的顺序可能不同,一些字段可能在CSV中,而其他字段可能不在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
所有_属性=[]
CSV.foreach('path/to/file')do |行|
属性={}
行。每个带有索引do的列,i|
下一步如果我%2!=0#每隔一列跳过一次
属性[column.to_sym]=行[i+1]
结束

所有的_属性好的,让它工作,除了它导入第一行两次与您的确切代码。有什么想法吗?我把
CSV.open
改为
CSV.foreach
@AdamEsterhuizen(doc:)谢谢你的帮助@MrYoshiji!