Rails 4 undefined方法`import&#39;对于导入csv文件的#<class:0xa874498> </class:0xa874498>

时间:2014-05-30 09:02:05

标签: ruby-on-rails csv ruby-on-rails-4

关于如何导入csv文件的this关注广播。

我的csv文件名为 stg_pound.csv ,其内容如下:

"FOREX RATES FOR DATES BETWEEN 2003-5-1 AND 2014-5-28, STG POUND",,,,
 Date,Currency,Buy,Sell,Mean
 01/01/03,STG POUND,147.5117,147.7939,147.653
 01/02/03,STG POUND,147.837,148.1767,148.007
 01/03/03,STG POUND,147.8006,148.1422,147.971
 01/04/03,STG POUND,148.0311,148.3722,148.202

我的应用设置如下:

我的外汇index.html.erb:

 <%= form_tag import_forexes_path, multipart: true do %>
   <%= file_field_tag :file %>
   <%= submit_tag "Import" %>
 <% end %>

forexes_controller.rb

def import
  Forex.import(params[:file])
  redirect_to root_url, notice: "Imported"
end

forex.rb

# == Schema Information
#
# Table name: forexes
#
#  id           :integer          not null, primary key
#  published_at :datetime
#  currency     :string(255)
#  buy          :float
#  sell         :float
#  mean         :float
#  created_at   :datetime
#  updated_at   :datetime
#

def import
    CSV.foreach(file.path, headers: true) do |row|
        Forex.create! row.to_hash
    end
end

的routes.rb

resources :forexes do
  collection  { post :import}
end

application.rb中

require 'csv'

当我尝试导入 stg_pound.csv 文件时,出现以下错误:

 undefined method `import' for #<Class:0xab2c6cc>

来自forex_controller.rb文件的以下行突出显示:

 Forex.import(params[:file])

但是我可以看到该文件已被选中,因为我在错误页面上看到了以下内容:

 Request

 Parameters:

 {"utf8"=>"✓",
 "authenticity_token"=>"mGm6jN7uvoRVjVbSDE/vpprIQnpjiL60s4rETHT9mPA=",
 "file"=>#<ActionDispatch::Http::UploadedFile:0xaa974dc @tempfile=#<Tempfile:/tmp/RackMultipart20140530-4261-z8fb9x>,
 @original_filename="stg_pound.csv",
 @content_type="text/csv",
 @headers="Content-Disposition: form-data; name=\"file\"; filename=\"stg_pound.csv\"\r\nContent-Type: text/csv\r\n">,
 "commit"=>"Import"}

起初我认为这是因为:文件没有包含在strong_parameters中所以我继续在forex_controller强参数中包含以下内容但它不起作用

def forex_params
  params.require(:forex).permit(:published_at, :currency, :buy, :sell, :mean, :file)
end

1 个答案:

答案 0 :(得分:2)

首先,你的import方法是一个实例,它需要是class。

def self.import
  # content
end

其次,您是从控制器Forex.import(params[:file])向它传递参数但不捕获它们。

def self.import(file)
  # content
end