[英]Ruby parse CSV file to print out the rows
我在Rails應用程序中上傳了文件,並且假設上傳正常,我想解析CSV文件。 您可以在下面看到注釋,該注釋指示我要在何處讀取CSV文件的行。 我怎樣才能做到這一點? 我使用了載波來上傳文件。
我這樣安裝
mount_uploader :file, LCFileUploader
這是我目前擁有的代碼
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
我得到這個錯誤:
undefined method `find_all_by_team_id' for #<Class:0x007fe14c40d848>
您可以使用CSV類 :
puts CSV.read(@lc_file.file.path)
或一次一行:
CSV.foreach(@lc_file.file.path) do |row|
puts row
end
除了CSV生成之外,還有其他一些問題:
lcfiles_path
或lcfile_path(@lc_file)
。 運行rake routes
(與運行Rails控制台的方式相同)以查看所有可用路徑的列表。 現在,如果您仍然有問題,我建議您發布另一個問題,因為這主要是關於CSV的生成,應該使用我在此答案開頭發布的代碼來解決。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.