简体   繁体   English

CSV导入中的模型错误-Ruby on Rails

[英]Model Error in CSV import - Ruby on Rails

I've been racking my brain for a while now and I can't figure out why my csv upload in my rails app is failing. 我已经花了一段时间的脑力了,我不知道为什么我在Rails应用程序中的csv上传失败了。 I have a simple model that converts two names in the csv to integers of foreign_ids. 我有一个简单的模型,可将csv中的两个名称转换为foreign_ids的整数。 The model works completely fine when executed manually in the console but for some reason it fails on the server. 在控制台中手动执行时,该模型可以正常工作,但是由于某种原因,它在服务器上失败。 I get the error message: undefined method `id' for nil:NilClass 我收到错误消息:nil:NilClass的未定义方法'id'

The model looks as follows: 该模型如下所示:

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

The problem must be in here somewhere. 问题一定在这里的某个地方。 Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks. 谢谢。

I'm an idiot. 我是个白痴。 The model was fine I just had a column mislabeled in my csv. 该模型很好,我的csv中只是有一个标签错误的列。

也许将: teamhash_id = teamhash.id更改为: teamhash_id = teamhash[:id] ,并且hashopponent_id = opponent_hash.id hashopponent_id = opponent_hash[:id] hashopponent_id = opponent_hash.id hashopponent_id = opponent_hash[:id]吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM