Rails CSV导入外键的开关字符串

时间:2015-06-08 22:21:37

标签: ruby-on-rails csv foreign-keys

我为我的Ruby App设置了CSV导入。一切都运行得很好,但是当我尝试上传一个字符串然后搜索一个id作为哈希中的外键输入时,我遇到了问题。我的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&#39;对于#

非常感谢任何帮助。

1 个答案:

答案 0 :(得分: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