Ruby on rails 外键的Rails CSV导入开关字符串
我已经为我的Ruby应用程序设置了CSV导入。一切都很好,但是当我尝试上传一个字符串,然后搜索一个id作为散列中的外键输入时,我遇到了问题。我的CSV模型如下所示:Ruby on rails 外键的Rails CSV导入开关字符串,ruby-on-rails,csv,foreign-keys,Ruby On Rails,Csv,Foreign Keys,我已经为我的Ruby应用程序设置了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, :heade
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
classplayer:symbol)do |行|
player\u hash=row.to\u hash
teamname=player\u hash[:team]
teamhash=Team.where(:name=>teamname)。首先
hashid=teamhash.id
player\u newhash=player\u hash.reject!{| k | k==:团队}
player\u newhash[:team\u id]=hashid
结束
玩家,创造!(播放器_newhash)
结束
结束
我相信这就是问题所在。当尝试执行时,我得到错误:
未定义的局部变量或方法“player\u newhash”#
非常感谢您的帮助。player\u newhash是foreach循环中的一个局部变量,因此您的create也需要在其中:
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
classplayer:symbol)do |行|
player\u hash=row.to\u hash
teamname=player\u hash[:team]
teamhash=Team.where(:name=>teamname)。首先
hashid=teamhash.id
player\u newhash=player\u hash.reject!{| k | k==:团队}
player\u newhash[:team\u id]=hashid
玩家,创造!(播放器_newhash)
结束
结束
结束
顺便说一句,我通过重构一秒钟来找出发生了什么事,从而得到了答案。。。如果有帮助,我的版本如下:
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
classplayer:symbol)do |行|
player\u hash=row.to\u hash
player\u newhash=player\u hash.reject!{| k | k==:团队}
player\u newhash[:team\u id]=查找团队(player\u hash[:team]).id
玩家,创造!(播放器_newhash)
结束
结束
私有的
def查找团队(团队名称)
团队。地点(名称:团队名称)。第一
结束
结束