字符串的未定义方法`original_filename' [英] undefined method `original_filename' for String
问题描述
我正在尝试在不使用诸如 paperclip
之类的 gem 的情况下实现 csv 上传功能.这是视图:
I'm trying to implement a csv upload functionality WITHOUT using gems such as paperclip
. Here's the view:
%h1 Add Users From CSV
= form_tag(:action => "upload",:multipart => true,:method => :post) do
= file_field_tag 'csv'
= submit_tag 'Upload'
这是控制器:
def upload
csv_io = params[:csv]
File.open(Rails.root.join('public', 'uploads', csv_io.original_filename), 'wb') do |file|
file.write(csv_io.read)
end
redirect_to root_path, :notice => "Successfully uploaded csv!"
end
但是当我上传名为 data.csv
undefined method `original_filename' for "data.csv":String
我只是按照官方的 Rails 指南进行操作,但仍然出现错误.任何人都可以提出一些解决方案吗?
I just followed the official Rails guide, but it's still getting error. Can anyone suggest some solutions?
注意:我只需要从 csv 文件中读取数据,不需要持久保存在服务器上.
NOTE: I just need to read data from the csv file and it does not need to be saved persistently on server.
推荐答案
您将参数传递给 form_tag
的方式,您的所有参数都被视为第一个 form_tag 的一部分
参数 url_for_options
,而不是部分转到第二个参数 options
(参见 http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-form_tag方法定义).
The way you're passing the arguments to form_tag
, all your arguments are getting treated as part of the first form_tag
parameter url_for_options
, instead of going in part to the second parameter options
(see http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-form_tag for the method definition).
根据 http://guides.rubyonrails.org/form_helpers.html# 上的指南上传文件,您可以使用以下语法来实现您想要的:
Per the guide at http://guides.rubyonrails.org/form_helpers.html#uploading-files, you can use the following syntax to achieve what you want:
form_tag({:action => "upload"},:multipart => true)
您不需要设置:method
,因为它默认为post
.
You don't need to set :method
because it defaults to post
.
这篇关于字符串的未定义方法`original_filename'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!