简体   繁体   English

Ruby解析CSV文件以打印出行

[英]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. 我在Rails应用程序中上传了文件,并且假设上传正常,我想解析CSV文件。 You can see the comment below that indicates where I would like to read the rows of the CSV file. 您可以在下面看到注释,该注释指示我要在何处读取CSV文件的行。 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 : 您可以使用CSV类

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: 除了CSV生成之外,还有其他一些问题:

  • 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) . 我想您想要类似lcfiles_pathlcfile_path(@lc_file) Run rake routes (the same way you ran rails console) to see a list of all available routes. 运行rake routes (与运行Rails控制台的方式相同)以查看所有可用路径的列表。

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. 现在,如果您仍然有问题,我建议您发布另一个问题,因为这主要是关于CSV的生成,应该使用我在此答案开头发布的代码来解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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