开发者

having trouble with CSV.parse not updating rows

开发者 https://www.devze.com 2023-04-11 12:23 出处:网络
I am running rails 3.0.1 with ruby 1.9.2p290 and trying to parse a CSV file using CSV (since from what I understand, CSV is using the fasterCSV code now).

I am running rails 3.0.1 with ruby 1.9.2p290 and trying to parse a CSV file using CSV (since from what I understand, CSV is using the fasterCSV code now).

I was following a nice writeup on setting this up for fasterCSV and only had to make minor changes to get it to work (change require to CSV instead of fasterCSV, etc.)

I can get the csv file to load into a table with the correct number of column counted out, but it things it is all one row no matter how many rows. For example, if my csv file had three rows with three columns, my import_table would show column number of 0,1,2 three times without incrementing the row number. So it does recognize the end of each row of my csv file, but isn't incrementing the row counter. What is it I am missing?

My csvcontroller looks like this:

            require 'csv'

            class Admin::CsvController < ApplicationController
              def import
              end

              def upload

                table = ImportTable.new :original_path => params[:upload][:csv].original_filename, 
开发者_开发知识库                                        :import_type => params[:type]
                uploaded_file = params[:upload][:csv].read

                CSV.parse(uploaded_file)  do |cells|
                  row_index = 0
                  column_index = 0
                  cells.each  do |cell|
                    table.import_cells.build :column_index => column_index, :row_index => row_index, :contents => cell
                    column_index += 1
                  end
                  row_index += 1
                end
                table.save
                redirect_to import_table_path(table)
              end
            end

I tried using .readline instead of .read, but that opened up another ball of wax.


Nevermind, I just discovered where my idiocy is on this. row_index = 0 needs to be outside the CSV.parse loop.

0

精彩评论

暂无评论...
验证码 换一张
取 消