首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从CSV导入和创建记录

从CSV导入和创建记录
EN

Stack Overflow用户
提问于 2016-04-10 03:30:59
回答 1查看 468关注 0票数 1

我正在尝试从CSV文件上传在配对表中创建记录。所提供的文件将采用这种格式。

代码语言:javascript
复制
supervisor,student,project_title
Bob,Alice,Web Site
Bob,Charlie,Web Application

问题是配对表不保存主管或学生的名称,而是保存它们的IDs,因此有必要在用户表中搜索这些给定的名称并选择它们的IDs,然后创建与这些ids和给定项目标题的配对。

下面的代码给了我太多的重定向错误,并在配对表中插入了一个空记录。

Pairing.rb

代码语言:javascript
复制
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

代码语言:javascript
复制
  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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-10 03:55:55

语句User.select(:id).where(name: supervisorName)不会像您期望的那样返回一个整数值。考虑使用User.find_by(name: supervisorName).id代替。

对于太多的重定向,请确保匹配您的pairings_path的操作不会重定向回自己或其他可能产生循环重定向的操作。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36525440

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档