2015-06-08 34 views
0

我爲我的Ruby應用程序設置了CSV導入。一切工作都很好,但是當我嘗試上傳一個字符串,然後搜索一個id作爲外鍵輸入到哈希中時,我遇到了問題。我的CSV模型看起來如下:用於外鍵的Rails CSV導入切換字符串

class Player < ActiveRecord::Base 
    belongs_to :team 
    validates :team_id, presence: true 
    def self.import(file) 
    CSV.foreach(file.path, headers: true, :header_converters => :symbol) do |row| 
     player_hash = row.to_hash 
     teamname = player_hash[:team] 
     teamhash = Team.where(:name => teamname).first 
     hashid = teamhash.id 
     player_newhash = player_hash.reject!{ |k| k == :team} 
     player_newhash[:team_id] = hashid 
    end 

    Player.create! (player_newhash) 
    end 
end 

我確信這是問題所在。當試圖執行我的錯誤:

未定義的局部變量或方法`player_newhash」爲#

任何幫助將不勝感激。

回答

0

player_newhash是你的foreach循環中的局部變量 - 讓你的創造將需要在那裏還有:

class Player < ActiveRecord::Base 
    belongs_to :team 
    validates :team_id, presence: true 

    def self.import(file) 
    CSV.foreach(file.path, headers: true, :header_converters => :symbol) do |row| 
     player_hash = row.to_hash 
     teamname = player_hash[:team] 
     teamhash = Team.where(:name => teamname).first 
     hashid = teamhash.id 
     player_newhash = player_hash.reject!{ |k| k == :team} 
     player_newhash[:team_id] = hashid 
     Player.create!(player_newhash) 
    end 
    end 
end 

順便說一句 - 我得到的答案通過重構爲第二,找出發生了什麼事情在......如果有幫助,我的版本看起來像這樣:

class Player < ActiveRecord::Base 
    belongs_to :team 
    validates :team_id, presence: true 

    def self.import(file) 
    CSV.foreach(file.path, headers: true, :header_converters => :symbol) do |row| 
     player_hash = row.to_hash 
     player_newhash = player_hash.reject!{ |k| k == :team} 
     player_newhash[:team_id] = find_team(player_hash[:team]).id 
     Player.create!(player_newhash) 
    end 
    end 

    private 

    def find_team(team_name) 
    Team.where(name: team_name).first 
    end 
end