【发布时间】:2016-04-10 03:30:59
【问题描述】:
我正在尝试通过 CSV 文件上传在 配对 表中创建记录。给出的文件将采用这种格式
supervisor,student,project_title
Bob,Alice,Web Site
Bob,Charlie,Web Application
问题是配对表不包含主管或学生的姓名,而是他们的 ID,因此有必要在 User 表中搜索这些给定名称并选择他们的 ID,然后使用这些 ID 创建配对并给定的项目标题。
下面的代码给了我太多重定向错误,并在配对表中插入了一条空记录。
配对.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
end
Pairings_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
【问题讨论】:
标签: ruby-on-rails ruby csv ruby-on-rails-4