I am in the process of learning Rails and am trying to create a file upload page to process CSV data without any use of my database or model. I am also trying to avoid using any gems such as Paperclip or Carrier-wave.
I have made some progress, but for some reason, my code is not working. I don't get the records that are in the CSV file displayed on the import.html.erb page.
When I click the upload button on my page: localhost:3000/upload, it redirects me properly to the expected page after submission, but the rows from file don't appear.
Does anyone have a clue why the page is not displaying the records from the CSV file?
The upload file view (index.html.erb):
<%= form_tag({:action => :import}, multipart: true) do %>
<%= file_field_tag :file %>
<%= submit_tag( "Import" ) %>
<% end %>
The controller (upload_controller.rb):
class UploadController < ApplicationController
def index
end
def import
rowarray = Array.new
myfile = params[:file]
CSV.foreach(myfile.path) do |row|
rowarray << row
@rowarraydisp = rowarray
end
end
end
The result view (import.html.erb):
<% @rowarraydisp.each do |row| %>
<%= row %>
<% end %>
<h1>File has been uploaded. Check</h1>
CSV.foreach(myfile.path) do |row|
rowarray << row
@rowarraydisp = rowarray
end
should be written:
@rowarraydisp = CSV.read(myfile.path)
Per the documentation for CSV.read
:
Use to slurp a CSV file into an Array of Arrays.
Your import.html.erb
file is used twice, for two different examples of your ERB. What is the actual file, and the actual code?
<% @rowarraydisp.each do |row| %>
<%= row %>
<% end %>
will try to send a sub-array row
from the CSV file to the browser, but, without an idea what that ERB or data is it's hard to say what the output will be other than the contents of a row of data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With