0

im trying to read csv file from form_tag, but when open the file with csv.read(file.path) throw the error "undefined method `path' ", someone know how to fix it?

my code in index.html.erb

    <%= form_tag("/main/import",method: "get",:multipart => true,name: "hola") do %>
    <%= file_field_tag :file %> 
    <%= submit_tag( "Import" ) %>
    <% end %>

in the main controller

 def import
    @myfile = params[:file]
    @rowarraydisp = CSV.read(@myfile.path)

end
StAx
  • 272
  • 1
  • 3
  • 16

1 Answers1

0

That's because depending on the size of the CSV file you're trying to upload, the type of file might either be a StringIO or TempFile object. So you may wan to take appropriate action, depending on which it is. See this answer for an explanation. Following that your code becomes something like:

file_data = params[:file]
if file.respond_to?(:read)
  csv_text = file.read
elsif file.respond_to?(:path)
  csv_text = File.read(file.path)
else
  logger.error "Bad file_data: #{file.class.name}: #{file.inspect}"
end
@rowarraydisp = CSV.parse(csv_text, :headers => true)

Also, you have specified method as GET in form_tag, in your case when uploading a form, you are posting data, so I'd just remove the method altogether or correctly specify the method as post.

Community
  • 1
  • 1
  • ok but when i do that throw this error "Missing or stray quote in line 1" -> @rowarraydisp = CSV.parse(csv_text, :headers => true) – StAx Nov 12 '14 at 16:58
  • ty :) just was the form of my file.csv, that throw the error – StAx Nov 12 '14 at 19:03