可选 csv 上传的 Paperclip/FasterCSV 处理出错
我有一个页面,用户可以将数据导入到该网站。以从 Excel 复制并粘贴到文本区域的形式,或上传 .csv 文件。
控制器检查 csv 是否已上传 - 如果是,则处理此内容,否则将处理粘贴的内容。 (假设用户现在只会选择一个选项)。
复制和粘贴部分工作正常,但是,当我尝试处理上传的 csv 文件时出现问题:
出现错误:
无法转换 ActionController::UploadedTempfile 转换为字符串
#events_controller
def invite_save
@event = Event.find(params[:id])
if params[:guest_list_csv]
lines = parse_csv_file(params[:guest_list_csv])
else
#csv file uploaded
lines = params[:guest_list_paste]
end
if lines.size > 0
lines.each do |line|
new_user(line.split)
end
flash[:notice] = "List processing was successful."
else
flash[:error] = "List data processing failed."
end
end
private
def parse_csv_file(path_to_csv)
lines = []
require 'fastercsv'
FasterCSV.foreach(path_to_csv) do |row|
lines << row
end
lines
end
def new_user(line)
#code to create new user would go here
end
我本质上是试图通过一个平滑的操作上传和处理 csv,而不是让用户按下“处理”按钮。
I have a page where a user can import data to the site. either in the form of copy and pasting into a text area from excel, or by uploading a .csv file.
The controller checks if a csv has been uploaded - if so it processes this, else it will process the pasted content. (working on the assumption the user will only choose one option for now).
The copy and paste part works perfectly, however, the problem arises when I try to process the uploaded csv file:
I get the error:
can't convert
ActionController::UploadedTempfile
into String
#events_controller
def invite_save
@event = Event.find(params[:id])
if params[:guest_list_csv]
lines = parse_csv_file(params[:guest_list_csv])
else
#csv file uploaded
lines = params[:guest_list_paste]
end
if lines.size > 0
lines.each do |line|
new_user(line.split)
end
flash[:notice] = "List processing was successful."
else
flash[:error] = "List data processing failed."
end
end
private
def parse_csv_file(path_to_csv)
lines = []
require 'fastercsv'
FasterCSV.foreach(path_to_csv) do |row|
lines << row
end
lines
end
def new_user(line)
#code to create new user would go here
end
I'm essentially trying to upload and process the csv in one smooth action, rather than have to get the user to press a "process" button.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在上面的第 #6 行,
问题是
params[:guest_list_csv]
不是实际的字符串,路径也不是,因为它是一个文件对象。您需要的是显式调用#path
。请尝试一下,看看是否可以解决您的问题。
On the line #6 above
The problem is
params[:guest_list_csv]
is not the actual string, neither is the path, since it's a file object. What you need is explicitly call#path
on it.Please try it and see if it fixes your problem.