简体   繁体   中英

Ruby parse CSV file to print out the rows

I have a file upload in my Rails application and I want to parse the CSV file assuming the upload went okay. You can see the comment below that indicates where I would like to read the rows of the CSV file. How can I do this? I used carrierwave for the file upload.

I mounted it as such

mount_uploader :file, LCFileUploader

Here is the code I currently have

require 'CSV'
class LCFilesController < ApplicationController
    def new
        authorize! :create, :lc_file
        @lc_file = LCFile.new
    end

    def create
        authorize! :create, :lc_file
        puts params
        @lc_file = LCFile.new(params[:lc_file])
        @lc_file.user_id = current_user.id
        if @lc_file.save

            #PARSE CSV HERE TO PRINT OUT THE ROWS OF THE CSV FILE
            CSV.foreach(@lc_file.file.path) do |row|
                puts row
            end

            redirect_to lc_path, :notice => 'New lc created!'
        else
            render :new
        end
    end
end

and I get this error:

undefined method `find_all_by_team_id' for #<Class:0x007fe14c40d848>

You can use the CSV class :

puts CSV.read(@lc_file.file.path)

or one row at a time:

CSV.foreach(@lc_file.file.path) do |row|
  puts row
end

Besides CSV generation there are a few more issues:

  • the redirect will not work after you send send some output. But even if it did, the output would not be seen, since you're redirecting.
  • the path you are redirecting to is incorrect (I believe that's why you get that error). I suppose you want something like lcfiles_path or lcfile_path(@lc_file) . Run rake routes (the same way you ran rails console) to see a list of all available routes.

Now if you still have issues, I suggest posting another question, as this one was mainly about CSV generation and that should be solved using the code I posted at the start of this answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM