ROR导入csv文件没有方法错误

时间:2015-03-31 14:09:41

标签: ruby-on-rails csv ibm-midrange

错误:

NoMethodError (undefined method `read' for nil:NilClass):
app/controllers/imports_controller.rb:5:in `upload'

我在之前的问题Adding CSV Import to a ROR application

中重写了我的csv上传例程

我在几年前发现了一个与我想要的问题类似的问题,但部分代码是用西班牙文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

*请注意,似乎有额外的结束,但在我添加它们之前,我收到了应用程序错误

模型/ 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

这是我用来上传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>

因此,对非方法错误的任何想法都会非常感激。正如你所知,我是Ruby新手,这是一个继承的应用程序,所以任何帮助都是最受欢迎的! 感谢

1 个答案:

答案 0 :(得分:1)

是的,它是nil。这不是你期望它的地方。您的form_for :dump在语义上构造了对象“转储”的表单。它由params中的对应密钥表示。所以,实际上,那个参数在那边:

params[:dump][:infile]