简体   繁体   中英

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. I have a simple model that converts two names in the csv to integers of 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

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.

也许将: 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]吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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