0

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>
1
  • (question should be closed. error I had was unrelated to what was posted or asked in this question) Commented Apr 1, 2013 at 20:56

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

10 Comments

That gave me a undefined method `find_all_by_team_id' for #<Class:0x007fe14c2c4658>
Does your upload actually work? If yes, how do you access the file? Did you replace the file I used with the mounted uploader column?
See update for how I mounted. Yes, the upload actually works. I'm not sure how to access the file. As of now, it saves when the upload is executed using the code above.
Can you say what's the output of LCFile.last.file.path if you run it from the rails console? (I assume you have at least one file uploaded)
sorry...but how do I do that? I'm on Mac using terminal to start my server
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.