Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.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解析轨道上的第一行_Ruby On Rails_Csv - Fatal编程技术网

Ruby on rails 忽略csv解析轨道上的第一行

Ruby on rails 忽略csv解析轨道上的第一行,ruby-on-rails,csv,Ruby On Rails,Csv,我正在使用中的代码解析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_

我正在使用中的代码解析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

当我在搜索如何跳过CSV/FasterCSV库的第一行时,这个问题不断出现,因此,如果您在这里结束,下面是一个解决方案

解决办法是。。。
CSV.foreach(“path/to/file.CSV”,{:headers=>:first_row})do|row


HTH.

如果您将第一行标识为标题,那么您将返回一个
对象,而不是一个简单的
数组

获取单元格值时,似乎需要在
对象上使用
.fetch(“行标题”)

这就是我想到的。我用我的
if
条件跳过
nil

CSV.foreach(“GitHubUsersToAdd.CSV”,{:headers=>:first_row})do|row|
username=row.fetch(“GitHub用户名”)
如果用户名
检查用户名
结束
结束

我会的

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

将循环它

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

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

您可以使用
做任何您想做的事情。不要忘记
headers:true

您还可以将hash
{:headers=>true}
作为第二个参数传递。这也行得通。
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
# #<CSV::Row "lesson_id":"5" "user_id":" 3">
# #<CSV::Row "lesson_id":"69" "user_id":" 95">
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
data_rows_only = csv.drop(1)
csv.drop(1).each do |row|
  # ...
end
CSV.foreach(File.join(File.dirname(__FILE__), filepath), headers: true) do |row|
    puts row.inspect
end