我现在已经绞尽脑汁了一段时间,我无法弄清楚为什么我在我的rails应用程序中上传的csv失败了。我有一个简单的模型,它将csv中的两个名称转换为foreign_ids的整数。在控制台中手动执行时,该模型完全正常,但由于某种原因,它在服务器上失败。我收到错误消息:未定义的方法`id'为零:NilClass
模型如下:
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
问题必定在某处。任何帮助将不胜感激。感谢。
答案 0 :(得分:1)
答案 1 :(得分:0)
也许改变:
teamhash_id = teamhash.id
至:
teamhash_id = teamhash[:id]
和hashopponent_id = opponent_hash.id
到hashopponent_id = opponent_hash[:id]
?