我正在尝试从CSV文件上传在配对表中创建记录。所提供的文件将采用这种格式。
supervisor,student,project_title
Bob,Alice,Web Site
Bob,Charlie,Web Application问题是配对表不保存主管或学生的名称,而是保存它们的IDs,因此有必要在用户表中搜索这些给定的名称并选择它们的IDs,然后创建与这些ids和给定项目标题的配对。
下面的代码给了我太多的重定向错误,并在配对表中插入了一个空记录。
Pairing.rb
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
supervisorName = row[0]
studentName = row[1]
title = row [2]
supervisorID = User.select(:id).where(name: supervisorName)
studentID = User.select(:id).where(name: studentName)
pair = Pairing.new
pair.supervisor_id = supervisorID
pair.student_id = studentID
pair.project_title = title
pair.save
end
endPairings_controller.rb
def new
@pairing = Pairing.new
end
def create
@pairing = Pairing.new(pairing_params)
if @pairing.save
redirect_to pairings_path, :notice => "Pairing Successful!"
else
redirect_to pairings_path, :notice => "Pairing Failed!"
end
end
def import
Pairing.import(params[:file])
redirect_to pairings_path, :notice => "Pairs Imported"
end发布于 2016-04-10 03:55:55
语句User.select(:id).where(name: supervisorName)不会像您期望的那样返回一个整数值。考虑使用User.find_by(name: supervisorName).id代替。
对于太多的重定向,请确保匹配您的pairings_path的操作不会重定向回自己或其他可能产生循环重定向的操作。
https://stackoverflow.com/questions/36525440
复制相似问题