the error:
NoMethodError (undefined method `read' for nil:NilClass):
app/controllers/imports_controller.rb:5:in `upload'
I reworked my csv upload routine from my earlier question Adding CSV Import to a ROR application
I had found a question that was asked several years ago that seemed similar to what I wanted but some of the code was in Spanish Ruby on Rails - Import CSV file
imports_controller:
class ImportsController < ApplicationController
def upload
logger.info "File loaded"
infile = params[:dump][:infile].read
n, errors = 0, []
@archive = []
CSV.parse(infile) do |row|
n += 1
# SKIP: header i.e. first row OR blank row
next if n == 1 or row.join.blank?
imports = Imports.build_from_csv(row)
if imports.valid?
imports.save
@archive << row
else
errors << row
end
end
logger.info errors
flash[:success] = "The CSV imported successfully"
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @archive }
end
end
end
*note that there seems to be extra end but until I added them I was getting an application error
models/imports.rb:
class Imports < ActiveRecord::Base
def self.build_from_csv(row)
#last_level = (row[5].downcase == "yes"
imports = Imports.new(:imports => "#{row[0]}}",
:cart_items => "#{row[1].titlesize}",
:cart_items_quantity => "#{row[2].titlesize}",
:cart_items_price => "#{row[3].titlesize}",
:cart_items_description => "#{row[4].titlesize}",
:cart_items_upc => "#{row[5].titlesize}",
:cart_items_sku => "#{row[6].titlesize}")
# :last_level=> last_level)
return imports
end
end
and here is the form call that I use to upload the csv:
<h3>Import CSV Order</h3>
<% form_for :dump, :url=>{:controller=>"imports", :action=>"upload"}, :html => { :multipart => true } do |f| -%>
<table">
<tr>
<td>
<label for="dump_file">
Select a CSV File :
</label>
</td>
<td >
<%= f.file_field :infile -%>
</td>
</tr>
<tr>
<td colspan='2'>
<%= submit_tag 'Submit' -%>
</td>
</tr>
</table>
So any thoughts on the no method error would be much appreciated. As you can tell I am new to Ruby and this was an inherited app so any help is most welcome! thanks
Yep, it's
nil
. It's not where you are expecting it to be. Yourform_for :dump
semantically constructs a form for object "dump". It is represented by a hash inparams
by the corresponding key. So, actually, that parameter is over there: