2014-05-30 41 views
0

我正在關注如何導入csv文件的this railcast。導入csv文件時,#<Class:0xa874498> Rails 4未定義方法`導入'

我的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文件中的以下行強調:

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"} 

Forex.import(params[:file]) 

不過,我可以看到該文件,因爲我看到下面的錯誤頁面已經被拾取

起初我以爲這是因爲:文件沒有被包含在strong_parameters中,所以我繼續並在forex_controller強參數中包括以下內容,但它不起作用

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

給你'進口method'在你的模型像這樣'self.import(文件)' – Pavan

+0

工作,但爲什麼它不是如果我不帶自前綴我的模型方法及其在軌道4,5工作? – Mutuma

+0

檢查@ Matt的回答! – Pavan

回答

2

首先,你的導入方法是一個實例,它需要是類。

def self.import 
    # content 
end 

其次,您從控制器Forex.import(params[:file])傳遞參數給它,但沒有捕獲它們。

def self.import(file) 
    # content 
end