undefined method `original_filename' for String

时间秒杀一切 提交于 2019-12-11 02:44:17

问题


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'

And here's the controller:

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

But I got this error message when I'm uploading a csv called data.csv

undefined method `original_filename' for "data.csv":String

I just followed the official Rails guide, but it's still getting error. Can anyone suggest some solutions?

NOTE: I just need to read data from the csv file and it does not need to be saved persistently on server.


回答1:


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).

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)

You don't need to set :method because it defaults to post.



来源:https://stackoverflow.com/questions/19755189/undefined-method-original-filename-for-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!