我一直在囤積我的大腦一段時間,我無法弄清楚爲什麼我的導航應用中的csv上傳失敗。我有一個簡單的模型,將csv中的兩個名稱轉換爲foreign_ids的整數。該模型在控制檯中手動執行時完全正常工作,但由於某種原因,它在服務器上失敗。我得到的錯誤信息:未定義的方法`ID」爲無:NilClassCSV導入中的模型錯誤 - Ruby on Rails
的模型如下所示:
require 'csv'
class Schedule < ActiveRecord::Base
belongs_to :team
belongs_to :opponent, :foreign_key => 'opponent_id', :class_name => 'Team'
def self.import(file)
CSV.foreach(file.path, headers: true, :header_converters => :symbol) do |row|
week_hash = row.to_hash
teamname = week_hash[:team]
teamhash = Team.where(:name => teamname).first
teamhash_id = teamhash.id
week_newhash = week_hash.reject!{ |k| k == :team}
week_newhash[:team_id] = teamhash_id
opponentname = week_hash[:opponent]
opponent_hash = Team.where(:name => opponentname).first
hashopponent_id = opponent_hash.id
week_newhash = week_newhash.reject!{ |k| k == :opponent}
week_newhash[:opponent_id] = hashopponent_id
Schedule.create!(week_newhash)
end
end
end
的問題必須在這裏的某個地方。任何幫助將不勝感激。謝謝。
在哪一行發生錯誤? – Pavan
兩個可能的地方'teamhash_id = teamhash.id'和'hashopponent_id = opponent_hash.id'和理由是'teamhash'或'opponent_hash'是零... –
我認爲錯誤是沒有id返回者hashopponent_id = opponent_hash.id。但我不明白爲什麼。這是來自控制檯的日誌。 ASC LIMIT 1 [[「name」,「Broncos」]]團隊負載(0.3ms)SELECT「teams」。* FROM「teams」WHERE「teams」。「name」= $ 1 ORDER BY「teams」。「 團隊負載(0.3ms)SELECT「teams」。* FROM「teams」WHERE「teams」。「name」IS NULL ORDER BY「teams」。「id」ASC LIMIT 1 重定向到http:// localhost:3000 /時間表 已完成302發現在4ms(ActiveRecord:0.5ms) – WelcomeChallenger