忽略csv解析Rails的第一行

我正在使用本教程中的代码来解析CSV文件并将内容添加到数据库表中。 我如何忽略CSV文件的第一行? 控制器代码如下:

def csv_import @parsed_file=CSV::Reader.parse(params[:dump][:file]) n = 0 @parsed_file.each do |row| s = Student.new s.name = row[0] s.cid = row[1] s.year_id = find_year_id_from_year_title(row[2]) if s.save n = n+1 GC.start if n%50==0 end flash.now[:message] = "CSV Import Successful, #{n} new students added to the database." end redirect_to(students_url) end 

 @parsed_file.each_with_index do |row, i| next if i == 0 .... 

当我在寻找如何跳过CSV / FasterCSV库的第一行时,这个问题不断涌现,所以这里的解决方案你最终来到这里。

解决方案是… CSV.foreach("path/to/file.csv",{:headers=>:first_row}) do |row|

HTH。

如果将第一行标识为标题,则会返回Row对象而不是简单的Array

当你获取单元格值时,似乎需要在Row对象上使用.fetch("Row Title")

这就是我提出的。 我正在使用if条件跳过nil

CSV.foreach("GitHubUsersToAdd.csv",{:headers=>:first_row}) do |row| username = row.fetch("GitHub Username") if username puts username.inspect end end

 require 'csv' csv_content =< 3 # it treats all lines as equal data parse_2 = CSV.parse csv_content, headers:true parse_2.size # => 2 # it ignores the first line as it's header parse_1 # => [["lesson_id", "user_id"], ["5", "3"], ["69", "95"]] parse_2 # => # 

在这里,它是有趣的部分

 parse_1.each do |line| puts line.inspect # the object is array end # ["lesson_id", "user_id"] # ["5", " 3"] # ["69", " 95"] parse_2.each do |line| puts line.inspect # the object is `CSV::Row` objects end # # # # 

所以我可以做到

 parse_2.each do |line| puts "I'm processing Lesson #{line['lesson_id']} the User #{line['user_id']}" end # I'm processing Lesson 5 the User 3 # I'm processing Lesson 69 the User 95 

使用这个简单的代码,您可以读取CSV文件并忽略第一行,即标题或字段名称:

 CSV.foreach(File.join(File.dirname(__FILE__), filepath), headers: true) do |row| puts row.inspect end 

你可以用row做你想做的事。 不要忘记headers: true

 data_rows_only = csv.drop(1) 

会做的

 csv.drop(1).each do |row| # ... end 

会循环它